首页 文章

使用swashbuckle在swagger文档中显示[Route]中的名称

提问于
浏览
3

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

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

1 回答

  • 0

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

    我们可以使用IOperationFilter检查Route Name的每个控制器方法,并将其注入我们的摘要中 . 我已经包含了一个示例类AttachRouteNameFilter来开始:

    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)));
            }
        }
    }
    

    接下来,在Swagger configuration中连接这个新的操作过滤器:

    config.EnableSwagger(c =>
    {    
        // Other configuration likely already here...
    
        c.OperationFilter<AttachRouteNameFilter>();
    });
    

    现在启动您的应用程序,观察您的路线名称在操作摘要之前是否可见 . 以下是我的路线名称为'GetMuffins'的示例:

    Example list operation, where the Route Name is visible in the summary.

    进一步阅读

相关问题