Theory question on generating the OpenAPI document during dotnet build with Microsoft.Extensions.ApiDescription.Server (OpenApiGenerateDocuments, OpenApiDocumentsDirectory, OpenApiGenerateDocumentsOptions, the GetDocument.Insider entry point), whether to commit the spec, and generating C# and TypeScript clients from it with Kiota or NSwag.
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.
"By default the built-in package only generates the document at runtime, when someone hits
/openapi/v1.json. For a contract you want it as a file at build time, and that's whatMicrosoft.Extensions.ApiDescription.Serverdoes. Once it's referenced, an MSBuild target runs after build: it starts your app through a tool called GetDocument.Insider, which runsProgram.csbut swaps Kestrel for a server that never listens, then asks the OpenAPI document provider for each registered document and writes it out. By default it lands inobj; I setOpenApiDocumentsDirectoryto put it in the project folder andOpenApiGenerateDocumentsOptionsto pick the file name.The catch is that your start-up code really runs. If
Program.csapplies EF Core migrations, connects to Key Vault or validates options against a real database, the build does that too, or fails on a build agent with no network. So I guard those with a check on the entry assembly name, or move them out of start-up entirely. I also make sure the document doesn't depend on environment-specific code, otherwise the build-time file and the runtime one differ.Then I commit the spec. That's the senior part: every pull request that changes the API shows a JSON diff a reviewer can read, and CI rebuilds and runs
git diff --exit-codeso nobody can change the contract without the file changing. Clients come from that file. For a .NET consumer or a React front end I'd use Kiota, Microsoft's generator, or NSwag if the team already uses it, run in CI so the client is never hand-edited. The mistake I see is generating clients from a running dev server: whatever was running on someone's laptop becomes the contract."
| Property | Purpose | Example |
|---|---|---|
OpenApiGenerateDocuments |
Turn build-time generation on or off | false on a fast inner-loop build |
OpenApiDocumentsDirectory |
Output folder (default obj) |
$(MSBuildProjectDirectory)/openapi |
OpenApiGenerateDocumentsOptions |
Extra arguments to the tool | --document-name v1 --file-name orders-api |
| Commit it | Don't commit | |
|---|---|---|
| Review | API changes visible in PR diffs | Must run the app to see changes |
| CI | Can fail on drift and run breaking-change checks | Nothing to compare against |
| Clients | Generated from a known file | Generated from whatever is running |
| Cost | Occasional merge conflicts in the JSON | None |
| Kiota | NSwag | |
|---|---|---|
| Languages | C#, TypeScript, Go, Java, PHP, Python, Ruby | C#, TypeScript |
| Style | Fluent request builders (client.Orders[id].GetAsync()), small runtime packages |
Single generated class per client, minimal runtime |
| Large APIs | Can generate a subset with --include-path |
Generates everything |
| Fit | Many consumers and languages, Microsoft Graph style | Teams already on NSwag, simple C#/TS clients |
We committed openapi/orders-api.json and added a CI step that rebuilds and fails on any diff. In the first month it caught 3 pull requests that changed a response shape without anyone noticing, including a property rename that would have broken the mobile app. The TypeScript client is generated with Kiota in the same pipeline, so the front end gets a compile error instead of a runtime undefined.
Checks that the candidate treats the OpenAPI document as a build artefact and contract, and understands the practical traps of generating it during build.
Green flags
Microsoft.Extensions.ApiDescription.Server and the output properties.Program.cs runs during build and guards side effects.Red flags
dotnet build
-> compile Orders.Api.dll
-> target GenerateOpenApiDocuments (from Microsoft.Extensions.ApiDescription.Server)
dotnet GetDocument.Insider.dll --assembly Orders.Api.dll ...
-> runs Program.Main via the host factory resolver
-> replaces IServer with a no-op server (never listens)
-> resolves the document provider registered by AddOpenApi
-> for each document name: generate and serialise
-> writes openapi/Orders.Api.json (or obj/ by default)
The app is built and its DI container is created exactly as at runtime, so AddOpenApi options, transformers and JsonSerializerOptions all apply. What doesn't happen is request processing.
Anything in Program.cs before app.Run() executes. Common offenders:
db.Database.Migrate() at start-upAddAzureKeyVault(...) configuration providers calling AzureValidateOnStart options that require secrets not present on build agentsThe documented trick is to check Assembly.GetEntryAssembly()?.GetName().Name == "GetDocument.Insider" and skip those steps. Better still, move migrations into a separate job (also safer in production).
CI
dotnet build -c Release (regenerates openapi/*.json)
git diff --exit-code openapi/ (fails if the committed spec is stale)
breaking-change check vs main (oasdiff or similar)
kiota generate / nswag (client from the committed file)
The spec becomes part of the review. A reviewer who sees a required property disappear knows to ask about consumers.
kiota generate -l CSharp -d openapi/orders-api.json -c OrdersClient -n Orders.Client -o src/Orders.Client. Uses Microsoft.Kiota.* runtime packages for HTTP, serialisation and authentication. kiota-lock.json records the settings so regeneration is reproducible.nswag openapi2csclient /input:openapi/orders-api.json /output:OrdersClient.cs or openapi2tsclient; can also run through an nswag.json file or MSBuild.dotnet openapi wrap NSwag for simple cases.Generated code is build output. Commit it or generate it in the build, but never edit it by hand; customise through generator settings or partial classes.
Microsoft.Extensions.ApiDescription.Server, set OpenApiDocumentsDirectory, run dotnet build and open the file.throw new Exception() inside an if (!isBuildTimeGeneration) block and confirm the build still succeeds.git diff.git diff --exit-code step to a GitHub Actions or Azure Pipelines workflow.Project file, guarded start-up and client generation.
<!-- Orders.Api.csproj -->
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<!-- write the spec into the repo, not obj/, so it can be committed -->
<OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)/openapi</OpenApiDocumentsDirectory>
<OpenApiGenerateDocumentsOptions>--file-name orders-api</OpenApiGenerateDocumentsOptions>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.*" />
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="10.0.*">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
// Program.cs
using System.Reflection;
var builder = WebApplication.CreateBuilder(args);
// true when dotnet build is generating the document, not serving requests
var isBuildTimeGeneration = Assembly.GetEntryAssembly()?.GetName().Name == "GetDocument.Insider";
if (!isBuildTimeGeneration)
{
// needs network and identity that a build agent doesn't have
builder.Configuration.AddAzureKeyVault(new Uri(builder.Configuration["KeyVault:Uri"]!), new Azure.Identity.DefaultAzureCredential());
}
builder.Services.AddOpenApi();
var app = builder.Build();
app.MapOpenApi();
app.MapGet("/orders/{id:int}", (int id) => TypedResults.Ok(new OrderDto(id, "AU-1001", 129.95m)))
.WithName("GetOrder");
app.Run();
public sealed record OrderDto(int Id, string Reference, decimal Total);
# CI: fail if the committed spec is stale, then generate a TypeScript client from it
dotnet build src/Orders.Api -c Release
git diff --exit-code src/Orders.Api/openapi/
dotnet tool install --global Microsoft.OpenApi.Kiota
kiota generate -l TypeScript -d src/Orders.Api/openapi/orders-api.json \
-c OrdersClient -o web/src/clients/orders
Program.cs. Why it is wrong: They run during dotnet build, so the build can migrate a real database, or fail on agents that have no network route or identity for those resources. Instead: Guard them with the GetDocument.Insider check, or move migrations to a separate deployment step.OpenApiDocumentsDirectory and file name. Why it is wrong: Parallel builds (dotnet build -m) overwrite each other's file, so the committed spec flips between versions and the drift check fails randomly. Instead: Give each project and document a unique --file-name, and generate from a single target framework.PrivateAssets=all.Build-time generation turns the OpenAPI document from a debugging aid into an artefact: something versioned, reviewed and tested like code. The senior judgement is mostly about the side effects of running Program.cs in a build and about where clients come from. I treat start-up side effects as a smell anyway (migrations at start-up race across instances), so the guard often pushes the design in a better direction.
It isn't always worth it. For a prototype whose API changes hourly, or an internal tool with one consumer in the same repository, a runtime document is enough and the extra build step is friction. For anything with external or mobile consumers, the committed spec pays for itself the first time it catches an unintended change.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Runtime document only | Prototypes, internal tools with one consumer | No diff, no contract checks | Anything with external consumers |
| Build-time, committed | Most APIs with clients | Guarded start-up, occasional JSON conflicts | Rapid prototyping where the API changes hourly |
| Design-first (spec written by hand, code follows) | Public or partner APIs, multiple teams | Two artefacts to keep in step | Small internal services |
| Kiota clients | Many languages, large APIs | Runtime packages, fluent style to learn | Teams standardised on NSwag |
| NSwag clients | Simple C#/TS clients | Fewer languages | Polyglot consumers |
| Refitter / openapi-generator | Teams that like Refit interfaces, or need a language Kiota lacks | Another tool's conventions | When Kiota or NSwag already cover your consumers |
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.
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.
How to tell it (STAR)
**S:** At [company] a backend property rename broke our mobile app for [two days] because nothing tied the API to its clients. **T:** I took on making contract changes impossible to miss. **A:** After a quick compatibility fix, I set up build-time OpenAPI generation, committed the spec, added a CI step that fails on drift, and switched both apps to Kiota-generated clients built from that file. **R:** In the first [month] the drift check caught [3] unintended shape changes in review, and we've had [no] contract-related production incidents since.
Last updated 23 Nov 2026.