skip to content

In ASP.NET Core 10 with Asp.Versioning, how do you publish one OpenAPI document per API version for the built-in Microsoft.AspNetCore.OpenApi generator?

level: seniorimportance: should knowfreq 30%

answer

  1. Asp.Versioning.OpenApi, new in 10
  2. AddApiExplorer: GroupNameFormat "'v'VVV"
  3. SubstituteApiVersionInUrl for v{version}
  4. MapOpenApi().WithDocumentPerVersion()
  5. app.DescribeApiVersions() lists them

basics

~10 s

Add Asp.Versioning.OpenApi, chain .AddApiExplorer(o => o.GroupNameFormat = "'v'VVV") and .AddOpenApi() on AddApiVersioning, then call app.MapOpenApi().WithDocumentPerVersion(). Each version gets its own document, such as /openapi/v1.json and /openapi/v2.json.

solid answer

~30 s

Asp.Versioning 10 ships **`Asp.Versioning.OpenApi`**, which integrates with `Microsoft.AspNetCore.OpenApi`. You chain it on the versioning builder: `AddApiVersioning(...).AddApiExplorer(o => { o.GroupNameFormat = "'v'VVV"; o.SubstituteApiVersionInUrl = true; }).AddOpenApi()`. The versioned API explorer puts every endpoint into a group per version, named by `GroupNameFormat` (`'v'VVV` turns 1.0 into `v1`), and `SubstituteApiVersionInUrl` writes `/api/v1/points` instead of `/api/v{version}/points` in the document. Then `app.MapOpenApi().WithDocumentPerVersion()` serves one document per version through the usual `/openapi/{documentName}.json` route, so `/openapi/v1.json` holds only v1 operations. `app.DescribeApiVersions()` returns the `ApiVersionDescription` list, including which versions are deprecated, so a UI can list one entry per version. The integration's `AddOpenApi(Action<VersionedOpenApiOptions>)` overload configures each version's document.

code

csharp · 17 lines
csharp
builder.Services.AddApiVersioning(options => options.ReportApiVersions = true)
    .AddApiExplorer(options =>
    {
        options.GroupNameFormat = "'v'VVV";          // 1.0 -> v1
        options.SubstituteApiVersionInUrl = true;     // /api/v1/points in the doc
    })
    .AddOpenApi();                                     // Asp.Versioning.OpenApi

var app = builder.Build();

app.MapOpenApi().WithDocumentPerVersion();             // /openapi/v1.json, /openapi/v2.json

foreach (var description in app.DescribeApiVersions())
{
    app.Logger.LogInformation("Document {Name} deprecated={Deprecated}",
        description.GroupName, description.IsDeprecated);
}

go deeper

for a junior

Recall that each API version gets its own document and that Asp.Versioning.OpenApi connects versioning to the built-in generator.

for a middle

Explain GroupNameFormat, SubstituteApiVersionInUrl and WithDocumentPerVersion, and what lands in each version's document.

for a senior

Keep per-version contracts accurate: deprecated versions flagged, neutral endpoints understood, URL parameters substituted, documents derived from declared versions.

for a principal

Decide how versioned documents are published and retired so consumers always know which contract they integrate against.

## Why per-version documents When v1 and v2 of the loyalty-points API run side by side, one document containing both is confusing: two `GET /api/v{version}/points/{memberId}` operations with different responses, and a client generator that cannot tell which to use. Each version is a separate contract, so each should have its own document. ## The packages in play - `Microsoft.AspNetCore.OpenApi` generates documents from ApiExplorer descriptions. - `Asp.Versioning.Mvc.ApiExplorer` adds a **versioned API explorer**: it assigns each endpoint description to a group per API version and registers `IApiVersionDescriptionProvider`. - `Asp.Versioning.OpenApi`, new in Asp.Versioning 10, connects the two. Its `AddOpenApi()` on `IApiVersioningBuilder` calls `AddApiExplorer()` for you and registers per-version document options. ## Wiring it 1. `builder.Services.AddApiVersioning(...)` as usual. 2. `.AddApiExplorer(options => { ... })`: - `GroupNameFormat = "'v'VVV"` names groups `v1`, `v2`; the `VVV` format writes major, then minor and status only when present. - `SubstituteApiVersionInUrl = true` replaces the `{version:apiVersion}` parameter with the actual version in documented paths, using `SubstitutionFormat`, which defaults to `VVV`. It matters only for URL-segment versioning. 3. `.AddOpenApi()` or `.AddOpenApi(options => ...)`, where `VersionedOpenApiOptions` exposes the version's `ApiVersionDescription`, its `OpenApiOptions` as `Document`, and `DocumentDescription` settings. 4. `app.MapOpenApi().WithDocumentPerVersion()`. The extension intercepts the document endpoint so a request for `v2` resolves the v2 document. The library's own example lists the documents for a UI with `app.DescribeApiVersions()`, which returns one `ApiVersionDescription` per version with its `GroupName`, `ApiVersion` and `IsDeprecated` flag. ## What each document contains | Request | Contains | |---|---| | `/openapi/v1.json` | endpoints implementing 1.0, paths like `/api/v1/points/{memberId}` | | `/openapi/v2.json` | endpoints implementing 2.0 | | version-neutral endpoints | appear in every version's document | Deprecated versions remain documented. The description's deprecation flag lets a UI mark them, and documentation options can describe the deprecation and sunset policy. ## Without the integration package The same result can be assembled by hand, because the built-in generator's default `ShouldInclude` keeps descriptions whose `GroupName` equals the document name: - configure `.AddApiExplorer(o => o.GroupNameFormat = "'v'VVV")`; - register `builder.Services.AddOpenApi("v1")` and `builder.Services.AddOpenApi("v2")`. The versioned explorer sets each description's group name to `v1` or `v2`, so each document picks up its own endpoints. The drawback is that every new version needs a new registration; `Asp.Versioning.OpenApi` derives documents from the versions the app actually declares. ## Pitfalls - Forgetting `GroupNameFormat`: groups are named from the version's default text, so document names do not look like `v1`. - URL-segment APIs without `SubstituteApiVersionInUrl` document a `version` path parameter the client must fill in by hand. - `app.MapOpenApi()` without `.WithDocumentPerVersion()` keeps serving one version-less document; Asp.Versioning 10's analyzer **AV0030** ("Missing WithDocumentPerVersion") flags it. ## Describing deprecation in each document `VersionedOpenApiOptions.DocumentDescription` is an `OpenApiDocumentDescriptionOptions` object that controls how a version's policies appear in its document: - `DeprecationNotice` and `SunsetNotice` are functions that turn a `DeprecationPolicy` or `SunsetPolicy` into notice text; returning null or empty shows no notice. - `HidePolicyLinks` (default false) leaves the policies' links out. The `ApiVersionDescription` objects that `DescribeApiVersions()` returns also carry `SunsetPolicy` and `DeprecationPolicy`, so a UI can show the dates beside each version. Registration noise is linted too: analyzer **AV0020** reports an `AddEndpointsApiExplorer()` call next to the versioned explorer, which already adds it. - Swashbuckle-era code that looped over `IApiVersionDescriptionProvider` calling `SwaggerDoc` per version is the older pattern; with the built-in generator, use the integration package.

  • Why does the v1 document show /api/v{version}/points/{memberId} with a version parameter?
    The routes use the `{version:apiVersion}` segment and `SubstituteApiVersionInUrl` is false, its default. Set it to true on the API explorer options and the document writes `/api/v1/points/{memberId}`, using `SubstitutionFormat`, which defaults to `VVV`.
  • Can you get per-version documents without Asp.Versioning.OpenApi?
    Yes. With `GroupNameFormat = "'v'VVV"` the versioned explorer sets each description's `GroupName`, and the built-in `ShouldInclude` keeps descriptions whose group name equals the document name, so `AddOpenApi("v1")` and `AddOpenApi("v2")` each collect their own endpoints. You must add a registration for every new version.

  • Asp.Versioning.OpenApi replaces Microsoft.AspNetCore.OpenApi rather than integrating with it.
  • MapOpenApi() alone splits the document by version once versioning is registered.
  • SubstituteApiVersionInUrl is needed for query-string versioning too.
  • Deprecated versions are removed from the generated documents automatically.
  • Per-version documents still require Swashbuckle's SwaggerDoc loop in .NET 10.

Assumes Asp.Versioning 10.2 on ASP.NET Core 10: Asp.Versioning.OpenApi is new in 10 and integrates Microsoft.AspNetCore.OpenApi.