Implements Asp.Versioning 10.x with Minimal APIs, one OpenAPI document per version, Deprecation (RFC 9745) and Sunset (RFC 8594) headers, and edge-only DTO mapping so versions share one domain.
I add Asp.Versioning 10.x (Asp.Versioning.Http for Minimal APIs, plus Asp.Versioning.Mvc.ApiExplorer and Asp.Versioning.OpenApi), declare a versioned API with route groups per version, and let API Explorer group endpoints into v1 and v2 so the built-in OpenAPI support emits one document per version.
For deprecation I mark 1.0 as deprecated, so api-deprecated-versions is reported, and send the Deprecation header (RFC 9745, @epoch-seconds) and Sunset header (RFC 8594, HTTP-date) with a Link to the migration guide.
Both versions call the same handler; only the request and response DTOs and their mapping differ. The trade-off: every extra version is more mapping code and tests, so I keep the version count low and measure v1 traffic to know when to remove it.
"On .NET 10 I use the Asp.Versioning 10.x packages, because 10.0 was the first release designed to integrate directly with the framework's built-in
Microsoft.AspNetCore.OpenApilibrary. Swashbuckle and NSwag are still maintained and perfectly viable, and teams with heavy Swashbuckle filters can keep them, but the .NET 9+ templates no longer include Swashbuckle, so for a new service I go with the built-in generator. For a Minimal API that meansAsp.Versioning.Http,Asp.Versioning.Mvc.ApiExplorerandAsp.Versioning.OpenApi. I callAddApiVersioningwith a URL segment reader andReportApiVersions, thenAddApiExplorerwith a group name format of'v'VVV, so each version becomes its own API Explorer group. Endpoints are declared withapp.NewVersionedApi(), a route group per major version, andHasApiVersion. The OpenAPI side then produces/openapi/v1.jsonand/openapi/v2.json, and Scalar or Swagger UI shows a version picker.For deprecation I do two things. I declare 1.0 as deprecated so the library reports it in
api-deprecated-versions, and I send the standard headers:Deprecation, which RFC 9745 made a proper standard in 2025 and uses a structured date like@1767225600, andSunsetfrom RFC 8594, which uses an ordinary HTTP-date and must not be earlier than the deprecation date. Both come with aLinkheader pointing at the migration guide. Client SDKs and API gateways can alert on these headers, but headers alone aren't communication: I also contact each consuming team or partner directly, with their own traffic numbers.The mistake I see is copying the whole controller into a
V2folder. Then a bug fix lands in v2 but not v1, and the versions drift. I keep one handler and one domain: the handler takes a version-neutral request record and returns a domain result, and each version's endpoint is a few lines that map its own DTO in and out. Contract tests pin each version's JSON. Versioning should be a thin layer at the edge, not a fork of the application."
| Piece | Package / API | Purpose |
|---|---|---|
| Version selection | AddApiVersioning, UrlSegmentApiVersionReader |
Reads v1 / v2 from the route |
| Endpoint mapping | NewVersionedApi, MapGroup(...).HasApiVersion(2.0) |
Assigns endpoints to versions |
| Version groups | AddApiExplorer(o => o.GroupNameFormat = "'v'VVV") |
One API Explorer group per version |
| OpenAPI documents | Built-in AddOpenApi + Asp.Versioning.OpenApi |
/openapi/v1.json, /openapi/v2.json |
| Deprecation signal | HasDeprecatedApiVersion / sunset policy, plus headers |
api-deprecated-versions, Deprecation, Sunset, Link |
| Header | Standard | Format | Meaning |
|---|---|---|---|
Deprecation |
RFC 9745 (March 2025) | Structured date: @1767225600 |
The resource is (or will be) deprecated from this moment; still works |
Sunset |
RFC 8594 (2019) | HTTP-date: Thu, 31 Dec 2026 13:00:00 GMT |
The resource will stop responding after this moment |
Link |
RFC 8288 | <https://docs/...>; rel="deprecation" |
Where to read about it |
GET /v1/orders/42 ─► V1 endpoint: map route → GetOrder(id) ─┐
├─► GetOrderHandler ─► domain + EF Core
GET /v2/orders/42 ─► V2 endpoint: map route → GetOrder(id) ─┘ │
▼ returns Order (domain)
V1 maps Order → OrderV1Dto V2 maps Order → OrderV2Dto
| Layer | Shared or per version? |
|---|---|
| Route group, DTOs, mappers, validators for the DTO shape | Per version |
| Handler / use case, domain model, business rules | Shared |
| Persistence, EF Core model | Shared |
| Contract tests (JSON snapshots) | Per version |
When v2 adds a genuinely new capability, the handler gets an optional input with a default that reproduces v1 behaviour, so v1's mapper passes the default and nothing forks.
HttpContext.GetRequestedApiVersion()) and the client id (subscription key, OAuth client id) on Activity.Current.We introduced v2 of an orders API when totals changed from a bare decimal to an amount plus currency. Both versions shared one handler; v1 had a 15-line mapper. We sent Deprecation and Sunset headers for 12 months and tracked calls by version and client id in Application Insights: v1 fell from [100]% to [3]% in six months, and two scheduled brownouts flushed out the last [two] integrators before removal.
Checks hands-on ability to implement versioning, per-version OpenAPI and standards-based deprecation without forking business logic.
Green flags
Red flags
endpoint metadata (ApiVersionMetadata)
│
▼
API Explorer (Asp.Versioning.Mvc.ApiExplorer)
groups endpoints by version → GroupName = "v1", "v2"
│
▼
Microsoft.AspNetCore.OpenApi document per group name
(Asp.Versioning.OpenApi registers one document per version
and adds version parameters, deprecation flags, sunset info)
│
▼
/openapi/v1.json /openapi/v2.json → Scalar / Swagger UI / Kiota
The built-in OpenAPI generator already works in terms of document names that match API Explorer group names. Before Asp.Versioning 10, people had to register each document by hand (AddOpenApi("v1"), AddOpenApi("v2")) and write a transformer to filter endpoints; the 10.x OpenAPI package does that wiring for you. If you're on 8.x (which still runs on .NET 10 via roll-forward), the manual approach still works.
They are different moments:
release v2 deprecate v1 sunset v1
─────┬────────────────┬──────────────────────────┬──────────►
│ v1 supported │ v1 works, Deprecation: │ v1 returns 410 Gone
│ │ header sent, no new │
│ │ features, fixes only │
RFC 9745 says the Sunset date must not be earlier than the Deprecation date. A deprecation date in the past means "deprecated now"; one in the future announces it.
Deprecation uses the Date type from Structured Field Values (RFC 9651): an @ followed by integer seconds since the Unix epoch. Sunset predates that and uses the classic IMF-fixdate. Getting the two formats mixed up is the most common implementation bug.
HasDeprecatedApiVersion(1.0) on the version set) makes api-deprecated-versions: 1.0 appear when ReportApiVersions is on, and marks operations deprecated: true in OpenAPI.options.Policies.Sunset(1.0).Effective(date).Link(uri)) make the library emit Sunset and Link headers for that version.Deprecation header support; check the version you pin. A small endpoint filter (as below) works on any version and makes the behaviour explicit.Rules I use:
Orders/V1/OrderDto.cs).Verify or approval tests) so a domain change that leaks into v1 fails CI.Add the API version to telemetry: Asp.Versioning exposes HttpContext.GetRequestedApiVersion(). Put it on the current Activity as a tag so Application Insights can chart requests by version and client.
/openapi/v1.json and /openapi/v2.json, and confirm v1 operations show deprecated: true.Deprecation, Sunset, Link and api-deprecated-versions headers.WebApplicationFactory asserting the Sunset date is not earlier than the Deprecation date.Activity tag for the version and query it in Application Insights with KQL.Two versions sharing one handler, one OpenAPI document per version, and deprecation headers on v1.
// Program.cs
using Asp.Versioning;
using System.Diagnostics;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<OrderService>();
builder.Services
.AddApiVersioning(o =>
{
o.DefaultApiVersion = new ApiVersion(2, 0);
o.ReportApiVersions = true;
o.ApiVersionReader = new UrlSegmentApiVersionReader();
})
.AddApiExplorer(o =>
{
o.GroupNameFormat = "'v'VVV";
o.SubstituteApiVersionInUrl = true;
})
.AddOpenApi(); // Asp.Versioning.OpenApi: one document per API version
var app = builder.Build();
app.MapOpenApi().WithDocumentPerVersion(); // /openapi/v1.json, /openapi/v2.json
var orders = app.NewVersionedApi("Orders");
// v1: deprecated, still served until the sunset date.
orders.MapGroup("/v{version:apiVersion}/orders")
.HasDeprecatedApiVersion(1.0)
.AddEndpointFilter(new DeprecationHeaders(
Deprecated: new DateTimeOffset(2026, 7, 1, 0, 0, 0, TimeSpan.Zero),
Sunset: new DateTimeOffset(2027, 7, 1, 0, 0, 0, TimeSpan.Zero),
Docs: new Uri("https://developer.example.com.au/orders/v1-to-v2")))
.MapGet("/{id:int}", async (int id, OrderService svc, CancellationToken ct) =>
await svc.FindAsync(id, ct) is { } o
? Results.Ok(new OrderV1Dto(o.Id, o.Total)) // v1 shape: bare decimal
: Results.NotFound());
// v2: current.
orders.MapGroup("/v{version:apiVersion}/orders")
.HasApiVersion(2.0)
.MapGet("/{id:int}", async (int id, OrderService svc, CancellationToken ct) =>
await svc.FindAsync(id, ct) is { } o
? Results.Ok(new OrderV2Dto(o.Id, new MoneyDto(o.Total, o.Currency)))
: Results.NotFound());
app.Run();
// One domain model and one service behind both versions.
public sealed record Order(int Id, decimal Total, string Currency);
public sealed class OrderService
{
public Task<Order?> FindAsync(int id, CancellationToken ct) =>
Task.FromResult<Order?>(id > 0 ? new Order(id, 120.50m, "AUD") : null);
}
public sealed record OrderV1Dto(int Id, decimal Total);
public sealed record MoneyDto(decimal Amount, string Currency);
public sealed record OrderV2Dto(int Id, MoneyDto Total);
// DeprecationHeaders.cs - explicit RFC 9745 + RFC 8594 headers, works on any library version.
using System.Globalization;
public sealed record DeprecationHeaders(DateTimeOffset Deprecated, DateTimeOffset Sunset, Uri Docs)
: IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext ctx, EndpointFilterDelegate next)
{
// RFC 9745: Sunset must not be earlier than Deprecation.
if (Sunset < Deprecated) throw new InvalidOperationException("Sunset precedes Deprecation.");
var headers = ctx.HttpContext.Response.Headers;
headers["Deprecation"] = "@" + Deprecated.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture);
headers["Sunset"] = Sunset.UtcDateTime.ToString("R", CultureInfo.InvariantCulture); // HTTP-date
headers.Append("Link", $"<{Docs}>; rel=\"deprecation\"; type=\"text/html\"");
// Tag telemetry so we can see who is still on v1.
System.Diagnostics.Activity.Current?.SetTag("api.version.deprecated", true);
return await next(ctx);
}
}
curl -i https://localhost:5001/v1/orders/42
# api-supported-versions: 2.0
# api-deprecated-versions: 1.0
# Deprecation: @1782864000
# Sunset: Thu, 01 Jul 2027 00:00:00 GMT
# Link: <https://developer.example.com.au/orders/v1-to-v2>; rel="deprecation"; type="text/html"
V2 folder. Why it is wrong: Fixes land in one version but not the other, and behaviour drifts. Instead: Share one handler; version only DTOs and mapping.Deprecation: true or an HTTP-date. Why it is wrong: RFC 9745 requires a structured field date (@epoch-seconds); true was only in the old draft. Instead: Emit @ plus Unix seconds, and an HTTP-date only for Sunset.Sunset date earlier than the Deprecation date. Why it is wrong: RFC 9745 forbids it and clients can't make sense of it. Instead: Validate the pair in code or tests.Activity as a tag (or a custom dimension) so KQL can group by it.The headers are cheap; the discipline is what matters. A version is only retired when you can prove nobody important still calls it, so I make the API version and the calling client part of every request's telemetry from the first release. With that, deprecation becomes a data-driven project with a burndown chart instead of a guess.
The other half is people. For each remaining client I want a named technical contact, an agreed migration date and a product owner on our side who will hold the line on the sunset date. I share the timeline at the start (deprecation, brownouts, sunset), send reminders at fixed intervals, and give internal stakeholders such as account managers the same list so nobody is surprised when a big customer's integration is on it.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Asp.Versioning 10.x + built-in OpenAPI | New .NET 10 services | Learning the version set model | Single-client internal APIs with no versioning need |
| Asp.Versioning + Swashbuckle | Existing services with many Swashbuckle filters | Two OpenAPI stacks in the estate | New services with no Swashbuckle investment |
Manual route prefixes (/v1, /v2 groups) |
Very small APIs, one or two versions | No version negotiation, no reporting headers | Public APIs needing proper 400s and reporting |
| Versioning at the gateway (API Management versions/revisions) | Many backends, central policy | Two places to configure; backend still has to support both shapes | When backends can't serve both contracts at all |
I also put the deprecation policy in the API guidelines (notice period, headers, brownouts, communication steps) so each team doesn't invent its own.
I make the committed build-time spec the contract and gate pull requests on it:
oasdiff breaking compares the PR's spec with main and the last released spec, and fails on removed paths or properties, new required request fields, narrowed enums or changed types.AddOpenApi("v1"), AddOpenApi("v2")), so breaking changes go into a new version while v1 stays frozen.The trade-off: CI becomes stricter and occasionally needs a deliberate override, but breaking changes become explicit decisions instead of production incidents.
Adding the Microsoft.Extensions.ApiDescription.Server package makes dotnet build produce the OpenAPI document. It launches your app's entry point with an inert server, asks the registered document provider for each document, and writes {Project}.json to obj (or to OpenApiDocumentsDirectory). Because your start-up code runs during build, guard anything that connects to databases or Key Vault.
I commit the spec: API changes then show up as diffs in pull requests, CI can fail when the regenerated file differs, and clients are generated from a file rather than a running server. For clients I use Kiota (C#, TypeScript, Go, Python...) or NSwag (C#, TypeScript).
The trade-off: a slightly slower build and a guarded Program.cs, in exchange for a contract you can review, diff and generate from.
A brownout is a short, announced window where the deprecated version deliberately fails, so clients that ignored the notices find out in a controlled way instead of on sunset day.
How to tell it (STAR)
**S:** We removed v1 of our consignments API on the published date, and one partner's nightly settlement job broke, so invoices didn't go out. **T:** I owned the API and had to restore service and fix how we retire versions. **A:** I re-enabled the v1 routes behind a flag within [40 minutes], then pulled 90 days of per-client traffic from Application Insights and found the partner was still making [3,000] v1 calls a night. I added Deprecation and Sunset headers, set a new date, ran two brownouts and walked their developer through the migration with their own numbers. **R:** They moved in [five weeks], we removed v1 with zero incidents, and the checklist I wrote has been used for [three] retirements since.
Last updated 23 Nov 2026.