📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show me how you version an ASP.NET Core 10 API with Asp.Versioning, generate a separate OpenAPI document for each version with the built-in OpenAPI support, and tell clients a version is deprecated using the Deprecation and Sunset headers. How do you keep v1 and v2 sharing the same business logic?

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.

Mid-Level Coding Intermediate api-versioning asp-versioning aspnet-core deprecation openapi web-api

🎯 Key points

  • Asp.Versioning.Http plus Asp.Versioning.Mvc.ApiExplorer and Asp.Versioning.OpenApi on .NET 10
  • NewVersionedApi, version sets and HasApiVersion / MapToApiVersion on route groups
  • One OpenAPI document per version from API Explorer group names (v1, v2)
  • Deprecation header (RFC 9745, structured date @epoch) and Sunset header (RFC 8594, HTTP-date)
  • Link header with rel=deprecation / rel=sunset pointing to the migration guide
  • Sunset must not be earlier than Deprecation
  • Versions differ in DTOs and mapping only; one handler and domain behind both
  • Per-version telemetry to know when v1 can be removed

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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.OpenApi library. 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 means Asp.Versioning.Http, Asp.Versioning.Mvc.ApiExplorer and Asp.Versioning.OpenApi. I call AddApiVersioning with a URL segment reader and ReportApiVersions, then AddApiExplorer with a group name format of 'v'VVV, so each version becomes its own API Explorer group. Endpoints are declared with app.NewVersionedApi(), a route group per major version, and HasApiVersion. The OpenAPI side then produces /openapi/v1.json and /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, and Sunset from RFC 8594, which uses an ordinary HTTP-date and must not be earlier than the deprecation date. Both come with a Link header 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 V2 folder. 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."


The pieces

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

Deprecation and Sunset headers

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

Sharing logic between versions

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.

Telemetry for versions

  • Tag every request with the requested version (HttpContext.GetRequestedApiVersion()) and the client id (subscription key, OAuth client id) on Activity.Current.
  • An Application Insights workbook charts requests by version and client; an alert fires if v1 traffic rises after deprecation (a new integration built on the old version).
  • A weekly report lists every client still on v1 with their call volume; that list drives direct contact.

Production example

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.

🔍 What the interviewer is checking

Checks hands-on ability to implement versioning, per-version OpenAPI and standards-based deprecation without forking business logic.

Green flags

  • Uses the current Asp.Versioning 10.x packages and API Explorer groups
  • Knows Deprecation uses a structured date and Sunset an HTTP-date
  • Shares one handler and versions only the DTOs
  • Measures per-version traffic before removal

Red flags

  • Duplicates whole controllers per version
  • One OpenAPI document mixing all versions
  • Deprecation communicated only by email
  • No plan for silent clients on sunset day

📚 Learn in depth

1. How the per-version document is produced

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.

2. Deprecated versus sunset

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.

3. Structured field dates

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.

4. Asp.Versioning's own deprecation signals

  • Mapping an endpoint to a deprecated version (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.
  • Sunset policies (options.Policies.Sunset(1.0).Effective(date).Link(uri)) make the library emit Sunset and Link headers for that version.
  • Recent 10.x releases add first-class Deprecation header support; check the version you pin. A small endpoint filter (as below) works on any version and makes the behaviour explicit.

5. Keeping versions thin

Rules I use:

  1. One MediatR or plain handler per use case, returning a domain result.
  2. Version-specific DTOs live next to their endpoints (Orders/V1/OrderDto.cs).
  3. Mapping is a static function per version, unit-tested.
  4. Contract tests snapshot each version's JSON (Verify or approval tests) so a domain change that leaks into v1 fails CI.
  5. When v1 is removed, you delete a folder; nothing in the domain changes.

6. Measuring adoption

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.

Try it yourself

  1. Build the sample below, open /openapi/v1.json and /openapi/v2.json, and confirm v1 operations show deprecated: true.
  2. Call v1 with curl and check Deprecation, Sunset, Link and api-deprecated-versions headers.
  3. Write a test with WebApplicationFactory asserting the Sunset date is not earlier than the Deprecation date.
  4. Generate a C# client from v2 with Kiota and check it ignores the v1 document entirely.
  5. Add an Activity tag for the version and query it in Application Insights with KQL.

💻 Code

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"

⚠ Common mistakes

  • Mistake: Copying controllers or handlers into a 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.
  • Mistake: Writing 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.
  • Mistake: A 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.
  • Mistake: Registering one OpenAPI document and showing every version in it. Why it is wrong: Generated clients mix v1 and v2 types and the docs mislead readers. Instead: One document per version, from API Explorer groups.
  • Mistake: Deprecating without per-client telemetry. Why it is wrong: You can't tell who still calls v1, so you can't remove it safely. Instead: Tag requests with version and client id, chart them in Application Insights or API Management analytics, and alert if v1 traffic grows.
  • Mistake: Logging the version only in free-text messages. Why it is wrong: You can't aggregate or alert on it. Instead: Put it on the Activity as a tag (or a custom dimension) so KQL can group by it.
  • Mistake: Treating headers as the only communication. Why it is wrong: Most client code never reads response headers. Instead: Also publish a changelog entry, email technical contacts and raise it in partner check-ins.
  • Mistake: Removing v1 on the sunset date without warning traffic. Why it is wrong: Silent clients break in production. Instead: Run brownouts and contact remaining callers first.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions per-version OpenAPI documents Why: Checks the documents are diffed in CI so breaking changes inside a version are caught.
    How to answer

    I make the committed build-time spec the contract and gate pull requests on it:

    1. Drift check: rebuild and fail if the generated spec differs from the committed one.
    2. Breaking-change check: 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.
    3. Lint: Spectral rules for house style (operationIds, ProblemDetails errors, naming).
    4. Versioning: one document per major version (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.

  2. When: Candidate mentions generating clients or committing the spec Why: Checks build-time OpenAPI generation and client generation with Kiota or NSwag.
    How to answer

    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.

  3. When: Candidate mentions the sunset date or removing v1 Why: Checks practical experience flushing out silent clients safely.
    How to answer

    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.

    • Response: I prefer exactly what clients will see after sunset, 410 Gone with a ProblemDetails body linking the migration guide, so the error is unambiguous. Some teams use 503 with Retry-After or fail only a percentage of calls for a gentler start; that is kinder to fragile clients but easier to mistake for an outage.
    • Run it: announce dates through email, the developer portal and the changelog, schedule a few of increasing length (10 minutes, 1 hour, 1 day) in Australian and partner business hours, as a gateway policy or feature flag you can switch off instantly.
    • Follow up: watch per-client errors and contact every client that hit it.

🛠 Real-world problems: how you handle them

v1 removal broke a partner's nightly sync
Situation
A logistics API on Azure App Service (Australia East) served [12] partners. v2 had been live for a year and v1 was removed on the date in the release notes. [Partner name]'s nightly settlement sync still called v1.
Signals
At 02:00 AEST Application Insights showed a spike of 404s on `/v1/consignments`; the partner raised a P1 at 07:30 because invoices hadn't generated. No `Deprecation` or `Sunset` headers had ever been sent; notice was by email only.
Investigation
Queried Application Insights `requests` by URL prefix and client id over 90 days: the partner made [3,000] v1 calls a night, all from one batch job. API Management analytics confirmed the subscription key. Their email contact had left the company months earlier.
Resolution
Immediate: redeployed the v1 route group behind a feature flag within 40 minutes and reran their sync. Long term: added `Deprecation`, `Sunset` and `Link` headers, set a new sunset 90 days out, ran two brownouts, and contacted the partner's technical owner directly with their traffic graph.
Prevention
A deprecation checklist in the API guidelines: per-client version telemetry dashboard, headers from deprecation day, brownouts, and a removal gate requiring under [0.5]% of traffic and named sign-off for each remaining client. Removal is a feature-flag flip first and a code deletion a month later.

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.

↩ Usually asked after

More in API Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me