liveBook · Manning

ApiVersion attribute

As explained in Building Web APIs with ASP.NET Core

The ApiVersion attribute is an ASP.NET Core API-versioning attribute that associates a controller or endpoint with one or more API versions.

The [ApiVersion] attribute assigns one or more API versions to a controller or Minimal API method. It identifies which versioned requests that endpoint supports; [MapToApiVersion] can specify versions for individual controller actions. section 3.3.3

Version a board-game controller

Place [ApiVersion("2.0")] on BoardGamesController and use [Route("v{version:apiVersion}/[controller]")]. A separate controller marked [ApiVersion("1.0")] can serve version 1. Minimal API mappings can likewise carry both [ApiVersion("1.0")] and [ApiVersion("2.0")]. section 3.3.3

// ...
 
builder.Services.AddApiVersioning(options => {
    options.ApiVersionReader = new UrlSegmentApiVersionReader();  #1
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.DefaultApiVersion = new ApiVersion(1, 0);
});
 
builder.Services.AddVersionedApiExplorer(options => {
    options.GroupNameFormat = "'v'VVV";                           #2
    options.SubstituteApiVersionInUrl = true;                     #3
});
 
// ...

Configure versioning services in Program.cs before using the attribute. This setup reads versions from URL segments, defaults unspecified versions to 1.0, and substitutes version numbers into routes. section 3.3.3

When publishing versioned routes through OpenAPI, configure the API explorer and Swagger documents so Swagger UI can show the versions. section 3.3.3

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Shows attribute placement and the required URI-versioning configuration; does not examine attribute internals.
Examples
Marks board-game controllers as versions 1.0 and 2.0 and marks Minimal API error endpoints with both versions.
What it assumes
Assumes an ASP.NET Core API with controllers or Minimal API methods; supplies the versioning-service setup.
What you can do after
Apply it in ASP.NET Core to assign versions to controllers or Minimal API methods.
How it connects
Connects API versioning to URI routing, MapToApiVersion, Minimal APIs, OpenAPI, and Swagger UI.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.