Show name from [Route] in swagger docs using swashbuckle
In an asp.net controller, when defining an action, we can specify the route name as part of the [Route] attribute. In the example below, I named this name "DeleteOrder". How do I show the name in the generated swagger documentation? Thank.
[HttpDelete]
[Route("order/{orderId}", Name ="DeleteOrder")]
[ProducesResponseType(typeof(void), 204)]
[ProducesResponseType(typeof(void), 400)]
public async Task<IActionResult> Delete(string orderId)
source to share
By default, Swagger UI will enumerate operations along their route. A non-intrusive way to include the route name in collapsed operations in the Swagger UI is to enter them in the summary of operations. Swashbuckle writes a summary field to the right of the HTTP method and route for each operation.
We can use IOperationFilter to check each controller method for the route name and inject it into our summary. I've included a sample AttachRouteNameFilter class 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)));
}
}
}
Then plug this new activity filter into Swagger Configuration :
config.EnableSwagger(c =>
{
// Other configuration likely already here...
c.OperationFilter<AttachRouteNameFilter>();
});
Now run the application and notice that the route name is displayed before the summary of the operation. Below is an example where my route name is "GetMuffins":
additional literature
source to share