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

编程入门 行业动态 更新时间:2024-10-24 06:32:06
本文介绍了使用 swashbuckle 在 swagger 文档中显示来自 [Route] 的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

解决方案

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

我们可以使用

进一步阅读
  • Swashbuckle 文档 - 操作过滤器
  • Swashbuckle 文档 - 包括 XML 注释

In the asp 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 Documentation - Operation Filters
  • Swashbuckle Documentation - Including XML Comments

更多推荐

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

本文发布于:2023-11-03 14:57:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555409.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:名称   文档   swashbuckle   swagger   Route

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!