Show Name from [Route] in swagger documentation using swashbuckle

对着背影说爱祢 提交于 2019-12-12 15:41:59

问题


In the asp .net controller when defining an action, we can provide a name to the route as part of the [Route] attribute. In the below example, I've given the name as 'DeleteOrder'. How do I get to showing the name in the generated swagger documentation? Thanks.

    [HttpDelete]
    [Route("order/{orderId}", Name ="DeleteOrder")]
    [ProducesResponseType(typeof(void), 204)]
    [ProducesResponseType(typeof(void), 400)]
    public async Task<IActionResult> Delete(string orderId)

回答1:


By default, Swagger UI will list operations by their route. A non-intrusive way to include the route name into collapsed operations in Swagger UI would be to inject them in your operation's summary. Swashbuckle writes the summary field to the right of the HTTP Method and Route for each operation.

We can use an IOperationFilter to check each controller method for a Route Name and inject it into our summary. I've included a sample class AttachRouteNameFilter to start with:

using Swashbuckle.Swagger;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;

namespace YourSpace
{
    public class AttachRouteNameFilter : IOperationFilter
    {
        public void Apply(Operation operation, 
            SchemaRegistry schemaRegistry, 
            ApiDescription apiDescription)
        {
            string routeName = apiDescription
                ?.GetControllerAndActionAttributes<RouteAttribute>()
                ?.FirstOrDefault()
                ?.Name;

            operation.summary = string.Join(" - ", new[] { routeName, operation.summary }
               .Where(x => !string.IsNullOrWhiteSpace(x)));
        }
    }
}

Next, wire up this new Operation Filter in your Swagger configuration:

config.EnableSwagger(c =>
{    
    // Other configuration likely already here...

    c.OperationFilter<AttachRouteNameFilter>();
});

Now start your app and observe that your route's name is visible before the operation's summary. Below is an example where my Route Name is 'GetMuffins':

Further Reading

  • Swashbuckle Documentation - Operation Filters
  • Swashbuckle Documentation - Including XML Comments


来源:https://stackoverflow.com/questions/43831986/show-name-from-route-in-swagger-documentation-using-swashbuckle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!