.NET › API Versioning

How can you version a single controller action to support multiple API versions without duplicating the entire controller class?

Advanced

Answer

Instead of separate controller classes per version, you can apply multiple [ApiVersion] attributes to one controller and use [MapToApiVersion("x.0")] on individual actions to indicate which specific version(s) an action supports, letting you share common actions across versions while only duplicating the ones that actually changed.
[ApiVersion("1.0")]
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/products")]
public class ProductsController : ControllerBase {
    [HttpGet]
    public IActionResult GetAll() => Ok(_products);  // shared across both versions

    [HttpGet("{id}")]
    [MapToApiVersion("2.0")]
    public IActionResult GetByIdV2(int id) => Ok(_v2Format);  // only in v2
}
Real-world example An API adds a new filtering capability only in v2's GetAll action while keeping the v1 GetById action completely shared, minimizing duplicated code across versions within one controller.

Common follow-ups: What happens if a request doesn't match any MapToApiVersion action?;How does this compare to maintaining fully separate controllers per version?