在 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] 的名称
发布评论