skip to content

With Asp.Versioning 10, how do you accept the version from a header or media type, and what happens when a request carries two conflicting versions?

level: seniorimportance: should knowfreq 35%

answer

  1. ApiVersionReader.Combine(...)
  2. HeaderApiVersionReader has no default header
  3. MediaTypeApiVersionReader reads the v parameter
  4. identical values collapse, different ones conflict
  5. 400 AmbiguousApiVersion

basics

~10 s

Set ApiVersioningOptions.ApiVersionReader to ApiVersionReader.Combine(...) with a HeaderApiVersionReader naming the header and, if wanted, a MediaTypeApiVersionReader for the v parameter. If the readers return two different version strings, the request gets 400 AmbiguousApiVersion.

solid answer

~40 s

Each reader extracts raw version strings from one place: `QueryStringApiVersionReader` (default parameter `api-version`), `UrlSegmentApiVersionReader` (the `{version:apiVersion}` route value), `HeaderApiVersionReader` (no default header, so you must name one, for example `x-api-version`) and `MediaTypeApiVersionReader` (the `v` parameter, as in `Accept: application/json;v=2.0`). `ApiVersionReader.Combine(...)` runs several and merges their results; identical strings collapse, compared case-insensitively. If more than one distinct value remains, such as `?api-version=2.0` with header `2`, Asp.Versioning answers **400** with the `AmbiguousApiVersion` problem. A value that cannot be parsed gets 400 `InvalidApiVersion`, a missing one 400 `ApiVersionUnspecified`, and a version no endpoint implements gets `UnsupportedApiVersionStatusCode`, 400 by default, except that a version taken from the URL path falls through to 404. Bodies are problem details when `AddProblemDetails()` is registered.

code

csharp · 10 lines
csharp
builder.Services.AddProblemDetails();
builder.Services.AddApiVersioning(options =>
{
    options.ReportApiVersions = true;
    options.ApiVersionReader = ApiVersionReader.Combine(
        new QueryStringApiVersionReader(),          // ?api-version=2.0
        new UrlSegmentApiVersionReader(),           // /api/v2/points
        new HeaderApiVersionReader("x-api-version"),// x-api-version: 2.0
        new MediaTypeApiVersionReader());           // Accept: application/json;v=2.0
});

go deeper

for a junior

Recall the four readers and that the default reads only the api-version query parameter and the URL segment.

for a middle

Explain how Combine merges values, why a header reader needs a name, and which status and problem code each client error produces.

for a senior

Diagnose clients failing with ambiguous or unspecified versions after a reader change, and keep the accepted sources few and documented.

for a principal

Standardize where versions travel across services and gateways so no layer introduces a second, conflicting version value.

## Readers extract, the matcher decides Asp.Versioning separates two jobs. An **API version reader** (`IApiVersionReader`) only extracts raw strings from the request. The routing **matcher policy** then parses them, compares them with the versions each candidate endpoint implements, and either picks an endpoint or substitutes a client-error endpoint. ## The built-in readers | Reader | Reads | Default | |---|---|---| | `QueryStringApiVersionReader` | query parameters | `api-version` | | `UrlSegmentApiVersionReader` | the route value behind `{version:apiVersion}` | uses the route constraint | | `HeaderApiVersionReader` | request headers | **none**: you must name the header | | `MediaTypeApiVersionReader` | a media-type parameter in `Content-Type` or `Accept` | parameter `v` | `ApiVersionReader.Default`, used when you configure nothing, is `Combine(new QueryStringApiVersionReader(), new UrlSegmentApiVersionReader())`. To support the loyalty-points mobile app, which sends a header, and partners who send a media-type parameter, configure: - `options.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader(), new HeaderApiVersionReader("x-api-version"), new MediaTypeApiVersionReader());` Keep `UrlSegmentApiVersionReader` in the combination if any routes use the `{version:apiVersion}` segment, because replacing the reader removes the default pair. ## How combining works The combined reader asks each reader in turn and gathers every value into a case-insensitive set: 1. One value in total: that is the requested version. 2. The same string from two places, such as `?api-version=2.0` and header `2.0`: the duplicates collapse to one value. 3. Two different strings, such as `2.0` and `2`, or `1.0` and `2.0`: the request is **ambiguous**. The comparison is on raw strings, before parsing, so `2` and `2.0` count as different even though they parse to the same version. Clients should send one spelling. ## The client errors | Situation | Status | Problem code | |---|---|---| | no version and none assumed | 400 | `ApiVersionUnspecified` | | version string cannot be parsed | 400 | `InvalidApiVersion` | | two different values | 400 | `AmbiguousApiVersion` | | parsed, but no endpoint implements it | `UnsupportedApiVersionStatusCode` (400) | `UnsupportedApiVersion` | The client-error endpoints write problem details through `IProblemDetailsService`; register `builder.Services.AddProblemDetails()` or the body is empty. With `ReportApiVersions` on, the unspecified, invalid and unsupported responses also carry the `api-supported-versions` header, which tells the client what it could have asked for; the ambiguous response does not. Two cases leave the 400 family: - When the version came from the URL path and no route implements it, or the API versions by URL segment only, the policy exits to routing's **404** instead. - When the API versions by media type only, an unimplemented version gets **415** if the request has a `Content-Type` header and **406** otherwise. ## Practical guidance - Name headers explicitly and document them; there is no implicit header. - Accept fewer places rather than more: every extra reader is another way for a request to become ambiguous. - When a gateway or SDK adds its own version parameter, check it uses the same spelling as the client, or requests start failing as ambiguous. - Changing `UnsupportedApiVersionStatusCode` to 404 is supported, but keep it consistent across services. ## Diagnosing a reader change When clients start failing right after the reader configuration changed, walk through the request: 1. Which places carry a version: query string, path segment, header or media type? 2. Which readers are active now? An assignment to `ApiVersionReader` replaced the default pair. 3. How many distinct raw strings do the active readers return? Zero means unspecified; two or more means ambiguous. 4. Does the parsed version have an endpoint? If not, the status is `UnsupportedApiVersionStatusCode`, or 404 for a version taken from the path. The problem `code` in the body names the branch directly, which is the fastest way to tell an ambiguous request from an unsupported one.

  • Why does adding HeaderApiVersionReader break clients that used /api/v2/points URLs?
    Assigning `ApiVersionReader` replaces the default, which was the query-string and URL-segment pair. If the new combination omits `UrlSegmentApiVersionReader`, the segment is no longer read, so those requests look unversioned and get 400 `ApiVersionUnspecified`. List every reader you still need in `Combine`.
  • Is a request with ?api-version=2.0 and header 2.0 ambiguous?
    No. The combined reader collects values in a case-insensitive set, so identical strings collapse into one value. It becomes ambiguous only when the strings differ, such as `2.0` and `2`, because the comparison happens before parsing.

  • HeaderApiVersionReader reads api-version by default, so new HeaderApiVersionReader() needs no header name.
  • If the query and header give different versions, the query string silently wins.
  • 2 and 2.0 from two readers are treated as one version because they parse equal.
  • Setting ApiVersionReader to a header reader keeps the default query and segment readers.
  • An unknown ?api-version value returns 404 Not Found unless you configure otherwise.

Assumes Asp.Versioning 10.2; reader defaults, the combining rule and the problem codes are read from that release's source.