Implementing API Versioning with Swagger in ASP.NET Core Web API

Building upon the foundational guide for integrating Swagger into an ASP.NET Core Web API, this article explores how to implement version control for API documentation.

1. Define API Version Enum

public enum ApiVersion
{
    /// <summary>
    /// Version 1
    /// </summary>
    V1 = 1,
    /// <summary>
    /// Version 2
    /// </summary>
    V2 = 2
}

2. Register Swagger Services

public void ConfigureServices(IServiceCollection services)
{
    #region Register Swagger Services
    services.AddSwaggerGen(options =>
    {
        typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
        {
            options.SwaggerDoc(version, new OpenApiInfo()
            {
                Version = version,
                Title = $"webapi {version}",
                Description = $"Asp.NetCore Web API {version}"
            });
        });
    });
    #endregion

    services.AddControllers();
}

3. Enable Swagger Middleware

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    // Enable Swagger middleware
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
        {
            options.SwaggerEndpoint($"/swagger/{version}/swagger.json", version);
        });
    });

    app.UseRouting();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

4. Apply ApiExplorerSettings Attribute to Controllers

namespace WebApi.Controllers.V1
{
    [Route("api/v1/[controller]")]
    [ApiExplorerSettings(GroupName = "V1")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        [Route("Get")]
        public string Get()
        {
            return "123456 v1";
        }
    }
}

namespace WebApi.Controllers.V2
{
    [Route("api/v2/[controller]")]
    [ApiExplorerSettings(GroupName = "V2")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        [Route("Get")]
        public string Get()
        {
            return "123456 v2";
        }
    }
}

5. Imoprtant Considerations

(1) When applying the ApiExplorerSettings attribute to controllers, ensure that the GroupName value matches exactly with the enum names defined in ApiVersion. Otherwise, the conttroller's API endpoints will not appear in the Swagger UI version list.

(2) The ApiVersion enum is optional; it is merely used here to dynamically retrieve vertion strings. An alternative approach would be to manually define the versions using a collection like new List { "V1", "V2" }.ForEach(...).

6. Runtime Outcome

Tags: aspnet-core swagger api-versioning web-api openapi

Posted on Thu, 02 Jul 2026 17:27:57 +0000 by seikan