Search code examples
asp.net-coreasp.net-web-apiswagger-uiswashbuckle.aspnetcore

Defaulting to the Latest API Version on Swagger UI


I have implemented Swashbuckle.AspNetCore.SwaggerUI (version 6.1.4) in my API. The API also configures Microsoft.AspNetCore.Mvc.Versioning (version 5.0.0).

This is now working, and I can set the API version at the top of the page to resolve to the various exposed endpoints.

My question is, can I configure the Swagger UI to default the version drop-down list at the top-right of the Swagger page to the highest API version. Currently, this is displayed as follows:

Select a definition - V1.0 (default)
                      V1.1
                      V2.0

I would like the UI to default, in this case to the latest published version (V2.0)

Here is my code:

        services.AddTransient<IConfigureOptions<SwaggerGenOptions>, SwaggerOptions>();

        services.AddSwaggerGen(
            options =>
            {
                options.EnableAnnotations();
                var xmlCommentsPath = GetXmlCommentsFilePath();
                if (File.Exists(xmlCommentsPath))
                {
                    options.IncludeXmlComments(xmlCommentsPath);
                }

                options.AddSecurityDefinition(
                    "Bearer", new OpenApiSecurityScheme
                    {
                        Name = "Authorization",
                        Type = SecuritySchemeType.ApiKey,
                        Scheme = "Bearer",
                        BearerFormat = "JWT",
                        In = ParameterLocation.Header,
                        Description = "JWT Authorization header using the Bearer scheme."
                    });

                options.AddSecurityRequirement(
                    new OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.SecurityScheme,
                                    Id = "Bearer"
                                }
                            },
                            Array.Empty<string>()
                        }
                    });
            });

public class SwaggerOptions : IConfigureOptions<SwaggerGenOptions>
{
    private readonly IApiVersionDescriptionProvider provider;


    /// <summary>
    /// Initializes a new instance of the <see cref="SwaggerOptions"/> class.
    /// </summary>
    /// <param name="provider">The <see cref="IApiVersionDescriptionProvider">provider</see> used to generate Swagger documents.</param>
    public SwaggerOptions(
        IApiVersionDescriptionProvider provider)
    {
        this.provider = provider;
    }


    /// <inheritdoc />
    public void Configure(
        SwaggerGenOptions options)
    {
        // add a swagger document for each discovered API version
        // note: you might choose to skip or document deprecated API versions differently
        foreach (var description in provider.ApiVersionDescriptions)
        {
            options.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(description));
        }
    }


    private static OpenApiInfo CreateInfoForApiVersion(
        ApiVersionDescription description)
    {
        var info = new OpenApiInfo
        {
            Title = "Demo API",
            Version = description.ApiVersion.ToString(),
            Description = "A sample application with Swagger, Swashbuckle, and API versioning.",
            Contact = new OpenApiContact {Name = "DemoApi"},
            License = new OpenApiLicense {Name = "MIT", Url = new Uri("https://opensource.org/licenses/MIT")}
        };

        if (description.IsDeprecated)
        {
            info.Description += " This API version has been deprecated.";
        }

        return info;
    }
}

public static class SwaggerConfigExtension
{
    public static IApplicationBuilder
        ConfigureSwaggerUi(
            this IApplicationBuilder app,
            IApiVersionDescriptionProvider apiVersionProvider)
    {
        return app.UseSwaggerUI(
            options =>
            {
                options.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.Full);
                foreach (var description in apiVersionProvider.ApiVersionDescriptions)
                {
                    options.SwaggerEndpoint(
                        $"/swagger/{description.GroupName}/swagger.json",
                        description.GroupName.ToUpperInvariant());
                }
            }
        );
    }
}

Any help/direction would be appreciated.


Solution

  • Install nuget Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer

    Then in Startup.cs

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApiVersionDescriptionProvider apiVersionDescriptionProvider)
        {
    .....
    
        app.UseSwaggerUI(c =>
                {
                    foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions.Reverse())
                    {
                        // Create the Swagger endpoints for each version
                        c.SwaggerEndpoint($"/swagger/" +
                            $"LibraryOpenAPISpecification{description.GroupName}/swagger.json",
                            description.GroupName.ToUpperInvariant());
                    }
                    c.RoutePrefix = ""; // swagger UI at the root index.html
                });
    ....
    }
    

    see this answer: click here