skip to content

In ASP.NET Core 10, how does build-time OpenAPI document generation work, and what can go wrong when it runs your Program.cs?

level: seniorimportance: nice to knowfreq 22%

answer

  1. Microsoft.Extensions.ApiDescription.Server package
  2. GenerateOpenApiDocuments target before Build
  3. OpenApiDocumentsDirectory defaults to obj
  4. entry point runs with a mock server
  5. GetDocument.Insider as the entry assembly

basics

~20 s

Adding Microsoft.Extensions.ApiDescription.Server makes every build run the app's entry point under a mock server, ask the registered generator for each document and write {ProjectName}.json to obj by default; startup code that needs real infrastructure must be guarded.

solid answer

~40 s

Build-time generation comes from the `Microsoft.Extensions.ApiDescription.Server` package. Its MSBuild props turn `OpenApiGenerateDocuments` and `OpenApiGenerateDocumentsOnBuild` on by default, so the `GenerateOpenApiDocuments` target runs during every `dotnet build`. It calls `dotnet-getdocument`, which loads your assembly through the `GetDocument.Insider` tool and **runs your entry point with a mock server**, then asks the services registered by `AddOpenApi` for each document. Files land in `OpenApiDocumentsDirectory`, which defaults to the intermediate `obj` folder, named after the project. `OpenApiGenerateDocumentsOptions` passes `--file-name`, `--document-name` or `--openapi-version`. Because `Program.cs` really executes, code that connects to a database, reads a secret store or validates required configuration can fail the build; the docs guard such code with an entry-assembly check against `GetDocument.Insider`.

code

xml · 10 lines
xml
<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.*" />
  <PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="10.0.*">
    <PrivateAssets>all</PrivateAssets>
  </PackageReference>
</ItemGroup>
<PropertyGroup>
  <OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)/contracts</OpenApiDocumentsDirectory>
  <OpenApiGenerateDocumentsOptions>--file-name flight-status --document-name v1</OpenApiGenerateDocumentsOptions>
</PropertyGroup>

go deeper

for a junior

Recall the package name and that, once added, every build writes the OpenAPI document as a file.

for a middle

Explain the MSBuild properties and their defaults, the obj output location, and the arguments passed through OpenApiGenerateDocumentsOptions.

for a senior

Diagnose builds broken by startup code running under the generator, and guard infrastructure registrations with the entry-assembly check.

for a principal

Decide whether the committed build-time document or the running endpoint is the contract of record, and which pipeline step owns publishing it.

## Why generate at build time The runtime endpoint from `MapOpenApi()` only exists while the app runs. Many workflows want the document as a **file** instead: committed next to the code so reviewers see contract changes in a pull request, attached as a build artifact, or fed to a client generator in the same build. ASP.NET Core supports this through the `Microsoft.Extensions.ApiDescription.Server` package, alongside `Microsoft.AspNetCore.OpenApi`. ## What the package wires into MSBuild The package ships a `.props` and a `.targets` file: | MSBuild property | Default | Effect | |---|---|---| | `OpenApiGenerateDocuments` | `true` | enables the feature and the `GenerateOpenApiDocuments` target | | `OpenApiGenerateDocumentsOnBuild` | value of `OpenApiGenerateDocuments` | ties the target into every build | | `OpenApiDocumentsDirectory` | `$(BaseIntermediateOutputPath)`, the `obj` folder | where files are written | | `OpenApiGenerateDocumentsOptions` | empty | extra arguments for the generator tool | So merely adding the package makes `dotnet build` produce documents. Two details from the source are worth knowing. First, one docs page says the default location is the app's output directory, while the package's props file sets `obj`, and the same page's own commands read from `obj`; the props file is what runs. Second, the target's command line is printed as a high-importance message, but the default terminal logger hides it; `dotnet build -tlp:v=d` or `--tl:off` shows it. ## How the document is produced 1. After compilation the target runs `dotnet-getdocument` against the built assembly. 2. That tool starts `GetDocument.Insider`, which loads your app and **invokes its entry point**. 3. The host is built with a **mock server** instead of Kestrel, so nothing listens on a port, but every line of `Program.cs` up to `Build()` runs: service registrations, configuration providers, options validation. 4. The tool resolves the document providers registered by `AddOpenApi` and writes each document. File naming: the default document is written as `{ProjectName}.json`; with several documents, others are suffixed, as in `{ProjectName}_internal.json`. ## Arguments you pass - `--file-name flight-status` renames the output file. - `--document-name v1` writes only that document. - `--openapi-version OpenApi3_0` selects the version written at build time. All three go into `<OpenApiGenerateDocumentsOptions>` in the project file. The version deserves care: the build-time tool passes a version explicitly, taken from `--openapi-version` and falling back to **3.1** when the argument is missing or invalid. A document pinned with `options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_0` in `AddOpenApi` is therefore still written as 3.1 at build time unless the argument says otherwise. The file is always JSON. ## What goes wrong Because the real entry point runs on a build agent, startup code meets an environment it was not written for: - **Required configuration** such as a connection string validated on start fails, and so does the build. - **Remote configuration providers**, for example a secret store, try to authenticate from the agent. - **Database work at startup**, such as applying migrations or seeding, attempts real connections. - **Environment-specific code paths**: the generation process does not run as your Development environment unless the agent's environment variables say so, so documents can differ from what `/openapi/v1.json` shows on a laptop. The docs' fix is to guard those registrations: - check `Assembly.GetEntryAssembly()?.GetName().Name == "GetDocument.Insider"` and skip them, or - move the work out of `Program.cs` startup into code that only runs when the server actually starts. ## Failures the tool reports - The tool waits **one minute** for each document; a startup that blocks longer, for example on a connection retry loop, times out. - A document that writes no content is reported as an error rather than an empty file. - If `OpenApiGenerateDocuments` is set to anything but `true`, invoking the target fails with a message saying generation is disabled. Set `<OpenApiGenerateDocumentsOnBuild>false</OpenApiGenerateDocumentsOnBuild>` when you want to invoke the `GenerateOpenApiDocuments` target explicitly, for instance only in the CI job that publishes the contract.

  • Why does the build fail on a CI agent with an error from your configuration validation?
    Build-time generation runs the real entry point. Options validated on start, or a required connection string missing on the agent, throw while the host is built, and the `GenerateOpenApiDocuments` target fails the build. Guard those registrations with the `GetDocument.Insider` entry-assembly check or supply harmless configuration for the generation run.
  • The running app serves OpenAPI 3.0 but the build-time file is 3.1. Why?
    The runtime endpoint serializes with the document's `OpenApiVersion` option, but the build-time tool passes a version explicitly: the `--openapi-version` argument, or 3.1 when it is missing. Add `--openapi-version OpenApi3_0` to `OpenApiGenerateDocumentsOptions` so both match.
  • How do you generate documents only in the CI job that publishes the contract?
    Set `OpenApiGenerateDocumentsOnBuild` to `false` in the project so ordinary builds skip it, then run `dotnet build -t:GenerateOpenApiDocuments` (or call the target from your own target) in that job. `OpenApiGenerateDocuments` must stay `true`, or the target errors that generation is disabled.

  • Build-time generation reads the compiled assembly statically and never runs Program.cs.
  • Microsoft.Extensions.ApiDescription.Client is the package that writes the server's document at build time.
  • The default output is the project folder, so files appear next to the .csproj.
  • Build-time generation starts Kestrel on a free port and calls /openapi/v1.json.
  • The build-time file always follows the OpenApiVersion set in the AddOpenApi options.

Assumes ASP.NET Core 10 and its Microsoft.Extensions.ApiDescription.Server package; the --openapi-version argument and the 3.1 default are 10 behaviour.