skip to content

In an ASP.NET Core controller versioned with Asp.Versioning 10, what do [ApiVersion], [MapToApiVersion] and [ApiVersionNeutral] do, and how do two actions share one route?

level: middleimportance: should knowfreq 45%

answer

  1. AddApiVersioning().AddMvc()
  2. [ApiVersion(2.0)] on the controller
  3. [MapToApiVersion] on the action
  4. explicit mapping beats implicit
  5. Deprecated = true on [ApiVersion]

basics

~20 s

[ApiVersion] on a controller declares the versions it implements, [MapToApiVersion] on an action narrows that action to one of them, and [ApiVersionNeutral] opts a controller or action out. Two actions on one route split versions this way; it needs AddApiVersioning().AddMvc().

solid answer

~40 s

With `Asp.Versioning.Mvc` registered through `AddApiVersioning(...).AddMvc()`, controllers declare versions with attributes. `[ApiVersion(1.0)]` and `[ApiVersion(2.0)]` on a controller say every action implements both; `[ApiVersion(1.0, Deprecated = true)]` still serves 1.0 but reports it as deprecated. On an action, `[MapToApiVersion(2.0)]` narrows it to one of the controller's declared versions. When two actions match the same route, the one explicitly mapped to the requested version wins over one that is only implicitly mapped, so an unmapped `Get` serves 1.0 and `[MapToApiVersion(2.0)] GetV2` serves 2.0. `[ApiVersionNeutral]` makes a controller or action match any version or none. For URL versioning the route uses the `apiVersion` constraint: `[Route("api/v{version:apiVersion}/points")]`. An action can take an `ApiVersion` parameter to read the requested version.

code

csharp · 16 lines
csharp
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[ApiVersion(1.0, Deprecated = true)]
[ApiVersion(2.0)]
[Route("api/v{version:apiVersion}/points")]
public class PointsController(IPointsLedger ledger) : ControllerBase
{
    [HttpGet("{memberId}")]                       // implicit: 1.0 and 2.0
    public int GetBalance(string memberId) => ledger.Balance(memberId);

    [HttpGet("{memberId}"), MapToApiVersion(2.0)] // explicit: wins for 2.0
    public PointsSummary GetSummary(string memberId, ApiVersion version) =>
        new(ledger.Balance(memberId), ledger.Tier(memberId), ledger.ExpiringSoon(memberId));
}

go deeper

for a junior

Recall which attribute declares versions, which narrows an action, and that AddMvc() is required for controllers.

for a middle

Explain implicit versus explicit mapping when two actions share a route, the apiVersion route constraint, and what Deprecated = true changes.

for a senior

Choose between one controller with mapped actions and separate controllers per version, keeping the old version frozen and deprecation visible.

for a principal

Set conventions for how controllers carry versions across a codebase so adding v3 is predictable and retiring v1 is cheap.

## Turning on controller versioning Controller support lives in `Asp.Versioning.Mvc`. It only applies after `builder.Services.AddApiVersioning(...).AddMvc()`; the attributes alone do nothing. The attributes live in the `Asp.Versioning` namespace. ## The attributes | Attribute | Placed on | Effect | |---|---|---| | `[ApiVersion(2.0)]` | controller, repeatable | declares an implemented version | | `[ApiVersion(1.0, Deprecated = true)]` | controller | still served, reported as deprecated | | `[MapToApiVersion(2.0)]` | action | narrows the action to one declared version | | `[ApiVersionNeutral]` | controller or action | matches any version, or none | | `[AdvertiseApiVersions(3.0)]` | controller | reports a version implemented elsewhere | Versions can be written as `double` (`2.0`), as major and minor integers, as a date for date-based group versions, or as a string with a status such as `"2.0-beta"`. ## Two actions on one route The loyalty-points controller keeps the v1 balance action and adds a v2 summary action on the same route: - The controller declares `[ApiVersion(1.0)]` and `[ApiVersion(2.0)]`. - `GetBalance` has no `[MapToApiVersion]`, so it is **implicitly** mapped to both versions. - `GetSummary` has `[MapToApiVersion(2.0)]`, so it is **explicitly** mapped to 2.0. - For a 2.0 request both actions are candidates; the explicit mapping wins. For a 1.0 request only `GetBalance` qualifies. The alternative is two controllers, `PointsController` with `[ApiVersion(1.0)]` and `PointsV2Controller` with `[ApiVersion(2.0)]`, on the same route template. Separate classes keep v1 untouched when v2 changes, at the cost of some duplication. ## Routes and the apiVersion constraint URL versioning needs the version in the template: `[Route("api/v{version:apiVersion}/points")]`. `apiVersion` is the constraint name Asp.Versioning registers (`RouteConstraintName` defaults to `apiVersion`). Query-string versioning needs no change to the route: `[Route("api/points")]` with `?api-version=2.0`. Route template syntax in general belongs to routing; the constraint is the versioning part. ## Reading the version An action can declare `ApiVersion version` as a parameter, as the library's own examples do, and receive the requested version. `HttpContext.RequestedApiVersion` returns it anywhere else. Avoid big `if (version == ...)` branches in one action; that couples the versions you meant to separate. ## Neutral controllers `[ApiVersionNeutral]` suits controllers that are not part of the versioned contract, such as a webhook receiver or a status page. A neutral endpoint matches whatever version the client sends, and also a request without one, so it never produces the 400 errors versioned endpoints do. ## Common mistakes 1. Forgetting `.AddMvc()`, so attributes are ignored and every action is unversioned. 2. Using `[MapToApiVersion(3.0)]` on an action when the controller never declared 3.0; mapping selects among implemented versions, so the action is never chosen for 3.0. 3. Putting `Deprecated = true` on the only version without a replacement, which tells clients to move to nothing. ## Which action serves which request With `PointsController` declaring 1.0 (deprecated) and 2.0, and the two actions in the example: | Request | Action | |---|---| | `GET /api/v1/points/42` | `GetBalance`, implicitly mapped | | `GET /api/v2/points/42` | `GetSummary`, explicitly mapped | | `GET /api/v3/points/42` | none: 404, because the version came from the URL path and nothing implements 3.0 | The library's documentation calls this **version interleaving** and recommends it for small differences only; the more an action changes between versions, the stronger the case for a separate controller class.

  • For a 2.0 request, both GetBalance and GetSummary match the route. Why does GetSummary win?
    GetBalance is only implicitly mapped to 2.0 through the controller's `[ApiVersion(2.0)]`, while GetSummary is explicitly mapped with `[MapToApiVersion(2.0)]`. Asp.Versioning prefers the explicit mapping for that version, so there is no ambiguity; for 1.0 only GetBalance qualifies.
  • What does Deprecated = true on [ApiVersion(1.0)] change for clients?
    Nothing about routing: 1.0 requests are still served. The version is listed as deprecated, so with `ReportApiVersions` on it appears in the `api-deprecated-versions` header instead of `api-supported-versions`. Retiring it is a separate step.

  • [ApiVersion] attributes work without AddMvc() on the versioning builder.
  • [MapToApiVersion(3.0)] adds version 3.0 even if the controller never declares it.
  • Deprecated = true makes 1.0 requests fail with 400.
  • Two actions on the same route always throw an ambiguous-match exception under versioning.
  • [ApiVersionNeutral] endpoints reject requests that do send a version.

Assumes Asp.Versioning.Mvc 10.2 on ASP.NET Core 10; attribute names, the apiVersion constraint name and ApiVersion parameter binding are read from that release.