使用 swashbuckle 在 swagger 文档中显示来自 [Route] 的名称 [英] Show Name from [Route] in swagger documentation using swashbuckle

查看:46
本文介绍了使用 swashbuckle 在 swagger 文档中显示来自 [Route] 的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 asp .net 控制器中定义动作时,我们可以为路由提供一个名称作为 [Route] 属性的一部分.在下面的示例中,我将名称命名为DeleteOrder".如何在生成的 swagger 文档中显示名称?谢谢.

 [HttpDelete][Route("order/{orderId}", Name ="DeleteOrder")][ProducesResponseType(typeof(void), 204)][ProducesResponseType(typeof(void), 400)]公共异步任务删除(字符串 orderId)

解决方案

默认情况下,Swagger UI 将按路径列出操作.将路由名称包含在 Swagger UI 中的折叠操作中的一种非侵入式方法是将它们注入到操作的摘要中.Swashbuckle 将汇总字段写入每个操作的 HTTP 方法和路由的右侧.

我们可以使用

进一步阅读

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)

解决方案

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 在 swagger 文档中显示来自 [Route] 的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆