2

I'm using ASP.NET Core 5, and Swagger. I know how to use Swagger, and it works properly.

Swagger is served on foo:5001/swagger - but I need to determine that URL programmatically at runtime.

How can I do that?


I already tried:

  1. Getting it by injecting IEnumerable<EndpointDataSource> into some helper/controller class, but that shows me all routes EXCEPT swagger's.

  2. Getting it while setting up endpoint routing and inspecting IEndpointRouteBuilder, but once again it shows me all routes EXCEPT swagger's.

lonix
  • 14,255
  • 23
  • 85
  • 176
  • 1
    Probably it's not what you're looking for, but it might be easier to configure that swagger route from a value stored in IConfiguration, and then you could grab the same value in your other component too. ¯\\_(ツ)\_/¯ – Leaky Mar 07 '21 at 16:52

1 Answers1

2

According to sources at https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/src/Swashbuckle.AspNetCore.SwaggerUI/SwaggerUIMiddleware.cs you can use an instance of class SwaggerUIOptions:

  1. Register instance in DI container:
var options = new SwaggerUIOptions 
{
    RoutePrefix = "swagger"
};
options.SwaggerEndpoint("/swagger/v1/swagger.json", "waiting_list v1");
services.AddSingleton(options);
  1. Use configured instance:
app.UseSwaggerUI(app.ApplicationServices.GetRequiredService<SwaggerUIOptions>());
  1. Inject instance to any controller/class:
public WeatherForecastController(ILogger<WeatherForecastController> logger, SwaggerUIOptions swaggerOptions)
{
}

Property RoutePrefix contains swagger prefix (without leading '/')

This idea works only if options object passed to UseSwaggerUI method (available since version 6.0.0). If UseSwaggerUI invoked using callback (like a UseSwaggerUI(a => { a.RoutePrefix = string.Empty; })) it won't work.

Igor Goyda
  • 1,949
  • 5
  • 10