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

📚 Interview question

Show me how you configure the built-in OpenAPI support in .NET 10. Use AddOpenApi and MapOpenApi, write document, operation and schema transformers, add a JWT bearer security scheme, and explain what changed when the default moved to OpenAPI 3.1.

Coding question on Microsoft.AspNetCore.OpenApi in .NET 10: registering and mapping documents, the three transformer types, adding a bearer security scheme and requirements, XML comments, and the OpenAPI 3.1 and Microsoft.OpenApi 2.x changes.

Intermediate Coding Intermediate aspnet-core dotnet-10 minimal-apis openapi security-schemes transformers

🎯 Key points

  • AddOpenApi(name, options) registers a named document; MapOpenApi maps /openapi/{documentName}.json, plus a .yaml route if you map one
  • Document transformers change the whole document (info, servers, security schemes); operation transformers change one operation; schema transformers change one type's schema
  • Transformers are lambdas or classes implementing IOpenApi*Transformer, registered on OpenApiOptions; classes are DI-activated and may be async
  • Transformers run in registration order, so register the one that adds a scheme before any that reference it
  • Bearer scheme added to Components.SecuritySchemes and referenced only from operations whose endpoint has authorisation metadata
  • OpenAPI 3.1 default in .NET 10: JSON Schema 2020-12, nullability as type arrays, OpenApiVersion option to fall back to 3.0
  • Microsoft.OpenApi 2.x (used by .NET 10, up from 1.x in .NET 9) changes types such as JsonSchemaType and references, breaking some .NET 9 transformer code
  • The document is generated on request at runtime: keep transformers fast and exception-safe, and add CacheOutput() or build-time generation

⏱ 30-second answer

You register a document with builder.Services.AddOpenApi("v1", o => ...) and serve it with app.MapOpenApi(), which maps /openapi/v1.json (a .yaml route also works in .NET 10). Customisation happens in transformers:

  • Document transformers change the whole document: Info, servers, security schemes.
  • Operation transformers change one operation: add a security requirement or a header.
  • Schema transformers change the schema of one type: formats, examples.

For JWT you add a bearer scheme to Components.SecuritySchemes and a requirement on operations that have IAuthorizeData metadata. In .NET 10 the output is OpenAPI 3.1 by default (JSON Schema 2020-12, nullability as type arrays) on Microsoft.OpenApi 2.x, so some .NET 9 transformer code needs updating. The trade-off: transformers are explicit and AOT-friendly but you write the plumbing Swashbuckle filters used to give you.

🗣 Full answer (senior)

How I would answer this in an interview

"Setting it up is two lines: builder.Services.AddOpenApi() registers a document called v1, and app.MapOpenApi() exposes it at /openapi/v1.json. I can register more than one, say AddOpenApi("public") and AddOpenApi("internal"), and use ShouldInclude to decide which endpoints go in each. In .NET 10 I can also map a YAML route and turn on GenerateDocumentationFile so my XML comments become summaries.

The real work is in transformers. A document transformer sees the whole OpenApiDocument, so that's where I set the title, contact and servers and add a bearer security scheme under components. An operation transformer runs per endpoint and gets the ApiDescription, so I can check whether the endpoint has authorisation metadata and only then add a security requirement; that way anonymous endpoints don't show a padlock in the UI. A schema transformer runs per type, so I use it to add formats or examples, for example marking a strongly typed ID as a string with a pattern. They run in registration order and can be classes resolved from DI, which is how I read the authentication schemes from IAuthenticationSchemeProvider instead of hard-coding them.

The .NET 10 change people trip over is OpenAPI 3.1. The document now follows JSON Schema 2020-12, so a nullable string is type: ["string", "null"] rather than nullable: true, and the library underneath moved to Microsoft.OpenApi 2.x, where types like JsonSchemaType and schema references changed. Transformers written for .NET 9 can fail to compile, and some older client generators only read 3.0, so I either upgrade them or set options.OpenApiVersion to 3.0. The mistake I see is people decorating every endpoint by hand instead of writing one operation transformer that derives the security requirement from metadata the endpoint already has."


The three transformer types

Type Runs Gets Typical use
Document Once per document OpenApiDocument, context Info, servers, security schemes, tag descriptions
Operation Once per endpoint OpenApiOperation, ApiDescription Security requirements, extra headers, deprecation
Schema Once per type OpenApiSchema, JsonTypeInfo Formats, examples, enum descriptions

OpenAPI 3.0 vs 3.1 (what you'll notice)

Area 3.0 (.NET 9 default) 3.1 (.NET 10 default)
Nullable nullable: true type: ["string", "null"]
Schema dialect Subset of JSON Schema JSON Schema 2020-12
Examples example examples array preferred
Library Microsoft.OpenApi 1.x Microsoft.OpenApi 2.x

Production example

We had 120 endpoints, 9 of them anonymous health or public catalogue endpoints. One operation transformer that adds the bearer requirement only when ApiDescription.ActionDescriptor.EndpointMetadata contains IAuthorizeData replaced 111 manual attributes, and the generated TypeScript client stopped sending tokens to the anonymous endpoints. Upgrading from .NET 9 to 10 needed changes in two transformers, about 20 lines, because of the Microsoft.OpenApi 2.x types.

🔍 What the interviewer is checking

Checks practical command of the .NET 10 built-in generator, its transformer model and the 3.1 upgrade, rather than Swashbuckle habits.

Green flags

  • Names all three transformer types and what each receives.
  • Adds the bearer requirement per operation from metadata.
  • Knows schemas come from System.Text.Json contracts.
  • Mentions OpenAPI 3.1, Microsoft.OpenApi 2.x and the 3.0 fallback.

Red flags

  • Only knows AddSwaggerGen and filters.
  • Adds a global security requirement and stops.
  • Unaware that .NET 10 changed the default spec version.

📚 Learn in depth

1. How the document is built

Start-up
  Endpoints + metadata  ->  API Explorer  ->  ApiDescription per endpoint

First request to /openapi/v1.json
  OpenApiDocumentService
    1. build paths and operations from ApiDescriptions
    2. build schemas from System.Text.Json JsonTypeInfo (same contract the serialiser uses)
    3. run schema transformers   (per type)
    4. run operation transformers (per operation)
    5. run document transformers  (once)
  -> serialise as JSON or YAML (OpenAPI 3.1 by default)

Schemas come from System.Text.Json's contract, not from reflection over your types. So JsonSerializerOptions (naming policy, JsonStringEnumConverter, [JsonIgnore]) directly shapes the document. That's a deliberate design choice: the document describes what is actually sent over the wire.

2. Transformer registration

  • Lambda: o.AddDocumentTransformer((doc, ctx, ct) => { ...; return Task.CompletedTask; }).
  • Class: o.AddDocumentTransformer<BearerSecuritySchemeTransformer>(), activated from DI per document generation, so it can take services in its constructor.
  • They run in the order you add them. Put the scheme-adding document transformer before anything that refers to the scheme.

3. Security schemes in OpenAPI

components:
  securitySchemes:
    Bearer: { type: http, scheme: bearer, bearerFormat: JWT }
paths:
  /orders:
    get:
      security:
        - Bearer: []        # only on operations that need it

A scheme is defined once in components; each operation (or the whole document) references it in security. Global security marks anonymous endpoints as protected too, which is why the per-operation approach is cleaner.

4. OpenAPI 3.1 and Microsoft.OpenApi 2.x

  • 3.1 aligns fully with JSON Schema 2020-12, so type can be an array and nullable disappears.
  • Microsoft.OpenApi 2.x models type as the JsonSchemaType flags enum and uses dedicated reference types (for example OpenApiSecuritySchemeReference) rather than an OpenApiReference property on every object.
  • If a consumer needs 3.0: services.AddOpenApi(o => o.OpenApiVersion = OpenApiSpecVersion.OpenApi3_0).

5. XML comments

With <GenerateDocumentationFile>true</GenerateDocumentationFile>, .NET 10's source generator reads /// comments on handlers and types at compile time and uses them for summaries, descriptions and parameter docs. No runtime XML parsing is involved, so it works with Native AOT.

Try it yourself

  1. Add the bearer transformer below and check that only endpoints with RequireAuthorization get a security block.
  2. Toggle OpenApiVersion between 3.0 and 3.1 and diff the output for a record with a nullable property.
  3. Add JsonStringEnumConverter to ConfigureHttpJsonOptions and watch enum schemas change from integers to strings.
  4. Turn on GenerateDocumentationFile and add a /// <summary> to a handler; confirm it appears in the operation.
  5. Register two documents with ShouldInclude filtering on group names and compare them.

💻 Code

Built-in OpenAPI with a bearer scheme added only where authorisation is required.

// Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
builder.Services.AddAuthorization();

builder.Services.AddOpenApi("v1", options =>
{
    // Document transformer as a lambda: title and contact
    options.AddDocumentTransformer((document, context, ct) =>
    {
        document.Info = new OpenApiInfo { Title = "Orders API", Version = "v1" };
        return Task.CompletedTask;
    });

    options.AddDocumentTransformer<BearerSecuritySchemeTransformer>(); // adds the scheme once
    options.AddOperationTransformer<BearerRequirementTransformer>();   // references it only where needed

    // Schema transformer: decimals as strings with a format hint for client generators
    options.AddSchemaTransformer((schema, context, ct) =>
    {
        if (context.JsonTypeInfo.Type == typeof(decimal))
            schema.Format = "decimal";
        return Task.CompletedTask;
    });
});

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapOpenApi();

app.MapGet("/health", () => TypedResults.Ok("ok"));                         // anonymous: no padlock
app.MapGet("/orders/{id:int}", (int id) => TypedResults.Ok(new Order(id, 42.50m)))
   .RequireAuthorization();                                                  // gets the bearer requirement

app.Run();

public sealed record Order(int Id, decimal Total);
// OpenApi/BearerTransformers.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi;

namespace Orders.Api.OpenApi;

// Activated from DI, so it can ask which authentication schemes really exist
internal sealed class BearerSecuritySchemeTransformer(IAuthenticationSchemeProvider schemes) : IOpenApiDocumentTransformer
{
    public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken ct)
    {
        var all = await schemes.GetAllSchemesAsync();
        if (!all.Any(s => s.Name == "Bearer")) return;

        document.Components ??= new OpenApiComponents();
        document.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
        document.Components.SecuritySchemes["Bearer"] = new OpenApiSecurityScheme
        {
            Type = SecuritySchemeType.Http,
            Scheme = "bearer",
            BearerFormat = "JWT"
        };
    }
}

// Adds the requirement only to operations whose endpoint has authorisation metadata
internal sealed class BearerRequirementTransformer : IOpenApiOperationTransformer
{
    public Task TransformAsync(OpenApiOperation operation, OpenApiOperationTransformerContext context, CancellationToken ct)
    {
        var metadata = context.Description.ActionDescriptor.EndpointMetadata;
        if (metadata.OfType<IAuthorizeData>().Any() && !metadata.OfType<IAllowAnonymous>().Any())
        {
            operation.Security ??= [];
            operation.Security.Add(new OpenApiSecurityRequirement
            {
                [new OpenApiSecuritySchemeReference("Bearer", context.Document)] = []
            });
        }
        return Task.CompletedTask;
    }
}
<!-- csproj: XML comments flow into the document in .NET 10 -->
<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);CS1591</NoWarn>
</PropertyGroup>

⚠ Common mistakes

  • Mistake: Adding a global security requirement to the document. Why it is wrong: Anonymous endpoints like /health show as protected, and generated clients send tokens everywhere. Instead: Add the requirement per operation, derived from IAuthorizeData metadata.
  • Mistake: Copying .NET 9 transformer samples into a .NET 10 project. Why it is wrong: .NET 10 moved from Microsoft.OpenApi 1.x to 2.x, which changed types such as JsonSchemaType and how references are modelled, so old code doesn't compile or produces wrong output. Instead: Use the 2.x model (OpenApiSecuritySchemeReference, JsonSchemaType flags).
  • Mistake: Expecting schema changes from attributes the serialiser ignores. Why it is wrong: Schemas come from System.Text.Json's JsonTypeInfo. Instead: Change JsonSerializerOptions or use a schema transformer.
  • Mistake: Hard-coding the auth scheme name in several places. Why it is wrong: Renaming the scheme silently breaks the document. Instead: Resolve IAuthenticationSchemeProvider in a DI-activated transformer.
  • Mistake: Doing expensive work (HTTP calls, database lookups) in transformers. Why it is wrong: The document is regenerated on each request to the OpenAPI endpoint and during build-time generation, so slow transformers make both slow. Instead: Keep them pure; cache anything static in a singleton and add CacheOutput() to MapOpenApi().
  • Mistake: Letting a transformer throw on unexpected input (a null Components, a type it didn't expect). Why it is wrong: One exception fails the whole document request with a 500 and breaks build-time generation in CI. Instead: Null-check (??=), guard on type, and cover the document with a WebApplicationFactory test that fetches it.
  • Mistake: Assuming every consumer accepts OpenAPI 3.1. Why it is wrong: Some API gateways and older client generators only accept 3.0. Instead: Check consumers; set OpenApiVersion = OpenApiSpecVersion.OpenApi3_0 if needed.
  • Mistake: Registering transformers in the wrong order. Why it is wrong: A transformer that references a scheme may run before the scheme exists. Instead: Register them in dependency order; they run in that order.

🏛 Senior insight: trade-offs

Transformers are the extension point, and the senior move is to derive documentation from metadata the endpoint already has (authorisation, tags, TypedResults) rather than duplicate it in attributes. That keeps the document and the behaviour in step, and lets you unit-test the document by fetching it through WebApplicationFactory and asserting on paths and security blocks.

Performance is rarely an issue but worth knowing: the built-in generator builds the document when /openapi/v1.json is requested, running every transformer. For a few hundred endpoints that is tens of milliseconds, fine in Development. If you do expose it in production, chain .CacheOutput() on MapOpenApi(), or generate it at build time and serve the static file. Transformer classes are activated per generation, so anything expensive and static (for example a list of scopes from configuration) belongs in a singleton they depend on.

Approach When it fits Cost When not to
Lambda transformers Small tweaks (info, one format) Hard to test in isolation Logic that needs services
Class transformers via DI Security schemes, cross-cutting rules A few more files One-line changes
Per-endpoint attributes or metadata A single odd endpoint Drifts from behaviour Rules that apply to many endpoints
Pin OpenAPI 3.0 A gateway or generator can't read 3.1 Lose 3.1 schema features Every consumer supports 3.1
CacheOutput() / build-time file Document served outside Development Stale until restart or rebuild Development, where you want live changes

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions reading endpoint metadata in an operation transformer. Why: Checks where the generator's input comes from.
    How to answer

    Every endpoint carries an EndpointMetadataCollection: a list of objects added by attributes, conventions like WithName, WithTags, RequireAuthorization, and types that implement IEndpointMetadataProvider such as TypedResults. Many features read that list:

    • API Explorer (IApiDescriptionGroupCollectionProvider) turns it into ApiDescriptions that the OpenAPI generator uses: Produces, ProducesProblem, WithTags, WithSummary.
    • LinkGenerator uses the endpoint name from WithName, which is also the operationId.
    • Authorisation, CORS, rate limiting and output caching middleware read it from HttpContext.GetEndpoint().

    The trade-off: metadata is one source of truth for docs and behaviour, but anything not in metadata (a hand-written IResult, a manual status code) is invisible to the docs.

  2. When: Candidate mentions generated clients or the 3.0 fallback for older generators. Why: Checks how the document is used beyond a runtime endpoint.
    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.

↩ Usually asked after

More in API Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me