.NET › API Versioning

How do you implement URL-based API versioning using the Asp.Versioning.Mvc package in ASP.NET Core?

Intermediate

Answer

The Asp.Versioning packages (successor to Microsoft.AspNetCore.Mvc.Versioning) let you register API versioning services, define supported versions per controller/action via [ApiVersion] attributes, and use a {version:apiVersion} route template placeholder so the framework automatically routes requests to the correct versioned controller or action.
builder.Services.AddApiVersioning(options => {
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.AssumeDefaultVersionWhenUnspecified = true;
});

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV1Controller : ControllerBase { }

[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV2Controller : ControllerBase { }
Real-world example An e-commerce API adds a ProductsV2Controller alongside the existing V1 controller when the product schema needs a breaking change, letting both versions run simultaneously in production.

Common follow-ups: How do you deprecate a version and communicate it via response headers?;How does versioning interact with Swagger/OpenAPI documentation generation?