Home > database >  Get Swashbuckle/Swagger route programmatically
Get Swashbuckle/Swagger route programmatically

Time:07-20

I'm using Swashbuckle with ASP.NET Core 6. It serves Swagger at /swagger.

For diagnostic purposes I need to detect that path programmatically at runtime - i.e. assuming swashbuckle is serving swagger at /swagger, then I want to be able to get that path.

I've tried various approaches, but they just give me my own routes. I can't find a way to determine routes added by swashbuckle.

I tried:

// inject IEnumerable<EndpointDataSource>
// ...
var routes = _endpointDataSources.SelectMany(source => source.Endpoints);

and:

var routes = app.Services.GetRequiredService<IActionDescriptorCollectionProvider>()
  .ActionDescriptors
  .Items.Where(x => x.AttributeRouteInfo != null)
  .Select(x => x.AttributeRouteInfo?.Template);

In both cases it enumerates all of my routes - whether they are from RazorPages or WebApi. But the swagger route is not included, even though it is running.

How do I get that path?

CodePudding user response:

Based on @lonix comment, Converting to Ans.

In case UseSwagger(), it does not create any endpoint but a middleware so when you call "/swagger", it checks request for swagger document and returns swagger document if found true. but in case of MapSwagger() it actually creates endpoint.

and yes you can swap it without breaking anything.

  • Related