Previous ASP.NET Core Web API Setup Caching in .NET Core Next

Versioning ASP.NET Core Web API

Versioning your ASP.NET Core Web API is essential for maintaining backward compatibility while evolving your application. Here's a complete guide to implementing API versioning in .NET Core, including strategies, setup, and best practices.

The most robust and flexible way to version a Web API in ASP.NET Core is by using the official API Versioning library from the ASP.NET team. This approach supports multiple versioning schemes and integrates smoothly with Swagger/OpenAPI for documentation.

🧭 Why API Versioning Matters

  • Backward Compatibility: Older clients continue to work even as new features are added.
  • Controlled Evolution: Introduce changes gradually without breaking existing integrations.
  • Client Flexibility: Consumers can upgrade at their own pace.

🔀 Common Versioning Strategies

Strategy Example Pros Cons
URL-based /api/v1/products Easy to implement and debug Clutters URI space
Query Parameter /api/products?api-version=1.0 Simple and flexible Not strictly RESTful
Header-based X-API-Version: 1.0 Clean URLs, supports negotiation Harder to test/debug
Media Type application/vnd.myapi.v1+json RESTful, supports content negotiation Complex setup

⚙️ Implementation in ASP.NET Core

1. Install NuGet Package

Add the following packages to your API project via the NuGet Package Manager or the command line. Asp.Versioning.Mvc Asp.Versioning.Mvc.ApiExplorer (for Swagger/OpenAPI integration)

2. Configure Services in Program.cs

Update your Program.cs file to register and configure the API versioning services. An example Program.cs configuration using the Asp.Versioning library is provided below, demonstrating how to add and configure API Versioning and API Explorer, and how to configure Swagger to support multiple API versions.

 
using Asp.Versioning;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();

// Add and configure API Versioning and API Explorer
builder.Services.AddApiVersioning(options =>
{
    options.ReportApiVersions = true;
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.DefaultApiVersion = new ApiVersion(1, 0);
}).AddMvc().AddApiExplorer(options =>
{
    options.GroupNameFormat = "'v'VVV";
    options.SubstituteApiVersionInUrl = true;
});

// Configure Swagger to support API versions
builder.Services.AddSwaggerGen(options =>
{
    var provider = builder.Services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>
        ();
    foreach (var description in provider.ApiVersionDescriptions)
    {
        options.SwaggerDoc(description.GroupName, new Microsoft.OpenApi.Models.OpenApiInfo
        {
            Title = "Versioned API",
            Version = description.ApiVersion.ToString()
        });
    }
});

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        var provider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>
            ();
        foreach (var description in provider.ApiVersionDescriptions)
        {
            options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json",
            description.GroupName.ToUpperInvariant());
        }
    });
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

3. Define Versioned Controllers

For URI path versioning, you can define different versions of your controllers. For a major version change (e.g., from v1.0 to v2.0), you typically create a new controller class. Minor versions (e.g., v1.0 and v1.1) can be handled within the same controller using [MapToApiVersion] on action methods for non-breaking changes.

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]
[ApiController]
public class ProductsV1Controller : ControllerBase
{
    [HttpGet]
    public IActionResult Get() => Ok("Product list from V1");
}

[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/products")]
[ApiController]
public class ProductsV2Controller : ControllerBase
{
    [HttpGet]
    public IActionResult Get() => Ok("Product list from V2 with enhancements");
}
 

Run and test the API

After implementing versioned controllers, run the project and access the Swagger UI, where you can select and test the different API versions.

✅ Best Practices

  • Use semantic versioning: Major versions for breaking changes.
  • Deprecate gracefully: Provide clear timelines and documentation.
  • Automated testing: Ensure all versions remain functional.
  • Document each version: Use Swagger with versioning support.
  • Keep controllers clean: Avoid mixing logic across versions.

⚠️ Precautions

  • Don't expose internal version logic to clients.
  • Avoid excessive fragmentation—only version when necessary.
  • Monitor usage of older versions to plan deprecation.

📈 Advantages

  • Smooth evolution of APIs
  • Better client experience
  • Easier maintenance and testing

📉 Disadvantages

  • Increased complexity in routing and documentation
  • Potential duplication of logic across versions
  • Requires disciplined version management
Back to Index
Previous ASP.NET Core Web API Setup Caching in .NET Core Next
*