How do you implement URL segment-based API versioning for controllers using [ApiVersion] and route templates?
Short answer
Apply [ApiVersion("1.0")] to a controller and include {version:apiVersion} in its route template; the versioning middleware then matches incoming requests' URL version segment to the correct controller, letting you maintain separate controller classes (or actions within one…
Advertisement
AModel answer
Apply [ApiVersion("1.0")] to a controller and include {version:apiVersion} in its route template; the versioning middleware then matches incoming requests' URL version segment to the correct controller, letting you maintain separate controller classes (or actions within one, using MapToApiVersion) per supported version.
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV1Controller : ControllerBase {
[HttpGet]
public IActionResult Get() => Ok(_v1Products);
}
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV2Controller : ControllerBase {
[HttpGet]
public IActionResult Get() => Ok(_v2ProductsWithNewFields);
}Real-world example
An inventory API introduces v2 with a restructured response shape while keeping v1 fully functional for existing integrators, both reachable via distinct, clearly versioned URLs (/api/v1/products and /api/v2/products).
Likely follow-ups
- How do you share common logic between V1 and V2 controllers without duplication?
- What happens if a client requests a version that doesn't exist?
Related topics