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.
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:
Info, servers, security schemes.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.
"Setting it up is two lines:
builder.Services.AddOpenApi()registers a document calledv1, andapp.MapOpenApi()exposes it at/openapi/v1.json. I can register more than one, sayAddOpenApi("public")andAddOpenApi("internal"), and useShouldIncludeto decide which endpoints go in each. In .NET 10 I can also map a YAML route and turn onGenerateDocumentationFileso 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 theApiDescription, 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 fromIAuthenticationSchemeProviderinstead 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 thannullable: true, and the library underneath moved to Microsoft.OpenApi 2.x, where types likeJsonSchemaTypeand 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 setoptions.OpenApiVersionto 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."
| 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 |
| 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 |
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.
Checks practical command of the .NET 10 built-in generator, its transformer model and the 3.1 upgrade, rather than Swashbuckle habits.
Green flags
Red flags
AddSwaggerGen and filters.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.
o.AddDocumentTransformer((doc, ctx, ct) => { ...; return Task.CompletedTask; }).o.AddDocumentTransformer<BearerSecuritySchemeTransformer>(), activated from DI per document generation, so it can take services in its constructor.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.
type can be an array and nullable disappears.type as the JsonSchemaType flags enum and uses dedicated reference types (for example OpenApiSecuritySchemeReference) rather than an OpenApiReference property on every object.services.AddOpenApi(o => o.OpenApiVersion = OpenApiSpecVersion.OpenApi3_0).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.
RequireAuthorization get a security block.OpenApiVersion between 3.0 and 3.1 and diff the output for a record with a nullable property.JsonStringEnumConverter to ConfigureHttpJsonOptions and watch enum schemas change from integers to strings.GenerateDocumentationFile and add a /// <summary> to a handler; confirm it appears in the operation.ShouldInclude filtering on group names and compare them.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>
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.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).JsonTypeInfo. Instead: Change JsonSerializerOptions or use a schema transformer.IAuthenticationSchemeProvider in a DI-activated transformer.CacheOutput() to MapOpenApi().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.OpenApiVersion = OpenApiSpecVersion.OpenApi3_0 if needed.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 |
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:
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.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.
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.
Last updated 23 Nov 2026.