Search code examples
asp.net-coreswaggerswagger-ui

Is there a way to use string interpolation in UseSwagger when trying to customize the route template?


I have run into a situation when I want to change the default route template in swagger. If I use string interpolation in the Route Template, the compiler will complaining about the documentName variable that I don't have in my code, but that part is required based on Swagger documentation. How would I solve it ?

var routePrefix = "api-docs";
app.UseSwagger(c => c.RouteTemplate = $"{routePrefix}/swagger/{documentName}/swagger.json"); // This is the error

app.UseSwaggerUI(c => {
   foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions) {
      c.SwaggerEndpoint($"/{routePrefix}/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
      c.RoutePrefix = routePrefix;
   }
});

Solution

  • Change {documentName} to {{documentName}} due to you use $. Besides, you need change the RouteTemplate and SwaggerEndpoint like below because the default routePrefix is swagger:

    var routePrefix = "api-docs";
    
    var apiVersionDescriptionProvider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
    app.UseSwagger(c => c.RouteTemplate = $"{routePrefix}/{{documentName}}/swagger.json"); // This is the error
    
    app.UseSwaggerUI(c => {
        foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions)
        {
            c.SwaggerEndpoint($"/{routePrefix}/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
            c.RoutePrefix = routePrefix;
        }
    });
    

    The request url should be: https://localhost:portNumber/api-docs/index.html