skip to content

In ASP.NET Core 10, how does endpoint metadata such as WithName, WithSummary and Produces reach the generated OpenAPI document?

level: middleimportance: must knowfreq 55%

answer

  1. ApiExplorer builds ApiDescription objects
  2. WithName becomes operationId
  3. IEndpointSummaryMetadata, last one wins
  4. IResult hides the response type
  5. GenerateDocumentationFile adds XML comments

basics

~20 s

The generator never reads handler bodies: ApiExplorer turns each endpoint's metadata into an ApiDescription, and the OpenAPI service maps it, WithName to operationId, WithSummary and WithDescription to summary and description, Produces and [ProducesResponseType] to responses.

solid answer

~40 s

`AddOpenApi()` reads endpoints through **ApiExplorer**. `EndpointMetadataApiDescriptionProvider`, registered by `AddEndpointsApiExplorer()`, describes Minimal API endpoints, and MVC's provider, registered by `AddControllers()`, describes actions. Each becomes an `ApiDescription` with its route, parameters, response types and the endpoint's metadata. The document service maps the attribute route name or `IEndpointNameMetadata` (`WithName`) to `operationId`, `IEndpointSummaryMetadata` (`WithSummary`, `[EndpointSummary]`) to `summary`, `IEndpointDescriptionMetadata` (`WithDescription`) to `description`, and response metadata from `Produces<T>`, `ProducesProblem` or `[ProducesResponseType]` to responses. A handler declared to return `IResult` exposes no type, so without `Produces<T>` its 200 has no schema. In .NET 10, `GenerateDocumentationFile` lets a source generator add XML-comment text too, and `ExcludeFromDescription()` keeps an endpoint out.

code

csharp · 13 lines
csharp
app.MapGet("/flights/{flightNumber}/status",
        async (string flightNumber, IFlightStatusStore store) =>
            await store.FindAsync(flightNumber) is { } status
                ? Results.Ok(status)
                : Results.NotFound())
   .WithName("GetFlightStatus")                       // operationId
   .WithSummary("Current status of one flight")       // summary
   .WithDescription("Gate, scheduled and estimated times for a flight number.")
   .Produces<FlightStatus>(StatusCodes.Status200OK)   // IResult hides this type
   .Produces(StatusCodes.Status404NotFound);

app.MapGet("/internal/cache-stats", () => "ok")
   .ExcludeFromDescription();

go deeper

for a junior

Recall which builder call fills which field: WithName for operationId, WithSummary and WithDescription for text, Produces for response types.

for a middle

Explain the chain from endpoint metadata through ApiExplorer's ApiDescription to the document service, and why an IResult return type loses the response schema.

for a senior

Diagnose a poor generated client from the document: missing operationIds, untyped responses or absent error responses, and fix them at the metadata, not by editing JSON.

for a principal

Decide which metadata conventions a team enforces so the published contract stays accurate, and where route-group conventions beat per-endpoint calls.

## The path from endpoint to document The built-in generator in `Microsoft.AspNetCore.OpenApi` does not reflect over handler code to guess what an endpoint returns. It reads **metadata**: objects attached to each endpoint by attributes or by builder calls such as `.WithName(...)`. The path has three steps: 1. **Endpoints carry metadata.** `app.MapGet(...).WithSummary("...")` adds an object implementing `IEndpointSummaryMetadata` to the endpoint's metadata collection; `[ProducesResponseType]` on an action does the same through MVC. 2. **ApiExplorer describes endpoints.** `EndpointMetadataApiDescriptionProvider` (added by `AddEndpointsApiExplorer()`, which `AddOpenApi()` calls for you) turns each Minimal API endpoint into an `ApiDescription`. For controllers, `AddControllers()` already registers MVC's ApiExplorer. An `ApiDescription` holds the HTTP method, relative path, parameter descriptions, supported response types and the raw `EndpointMetadata`. 3. **The document service maps descriptions.** For every description that passes `ShouldInclude`, it builds an operation and fills it from the description. ## What maps where | Document field | Comes from | Typical API | |---|---|---| | `operationId` | attribute route name, else `IEndpointNameMetadata` | `WithName`, `[EndpointName]`, `[HttpGet(Name = ...)]` | | `summary` | `IEndpointSummaryMetadata` | `WithSummary`, `[EndpointSummary]` | | `description` | `IEndpointDescriptionMetadata` | `WithDescription`, `[EndpointDescription]` | | `tags` | `ITagsMetadata`, else the controller name | `WithTags`, `[Tags]` | | `responses` | response-type metadata plus inference | `Produces<T>`, `ProducesProblem`, `[ProducesResponseType]` | | parameters, body | parameter descriptions | route, query, header and body binding | When the same kind of metadata is added twice, the service takes the **last** one, so a summary set on a single endpoint overrides one set earlier by a convention. ## Responses: declared versus inferred Response types are where most documents go wrong: - A handler whose declared return type is a concrete type, such as `FlightStatus`, yields a 200 response with that schema. - A handler declared to return **`IResult`** is treated like `void`. `Results.Ok(status)` decides the body at run time, so ApiExplorer records a 200 with **no schema**. Add `.Produces<FlightStatus>()` to describe it. - `ProducesProblem(404)` declares a response whose content type defaults to `application/problem+json`; `ProducesValidationProblem()` defaults to 400. - Controllers declare each status with `[ProducesResponseType]`. In .NET 10 it, `[Produces]` and `[ProducesDefaultResponseType]` gain a `Description` for the response. Typed results that announce their own response types are covered with Minimal API results; the point here is that whatever produces the metadata, the document only sees metadata. ## Parameters and schemas Parameters and bodies come from the same descriptions. A route parameter is always marked required; a query or header parameter is required when it is non-nullable or carries `[Required]`. `System.ComponentModel.DescriptionAttribute` on a parameter or property becomes its `description`. Validation attributes shape the schema: `[Range]` writes `minimum` and `maximum`, `[RegularExpression]` writes `pattern`, `[MaxLength]` writes `maxLength`, and `[Required]` on a property adds it to the schema's `required` list. Request content types come from binding, or from `Accepts<T>("application/xml")` when a handler reads the body itself. ## XML comments in .NET 10 Setting `<GenerateDocumentationFile>true</GenerateDocumentationFile>` in the project lets a source generator shipped with `Microsoft.AspNetCore.OpenApi` read `<summary>`, `<remarks>`, `<param>`, `<response>` and `<example>` at compile time and apply them to the document. One trap: a `<response code="404">` tag **describes** a response that metadata already declares. It does not add a 404 by itself; without `Produces(404)` or `[ProducesResponseType(404)]` the response is left out. ## Keeping endpoints out - `.ExcludeFromDescription()` or `[ExcludeFromDescription]` on a Minimal API endpoint. - `[ApiExplorerSettings(IgnoreApi = true)]` on a controller or action. - `MapOpenApi()` already excludes its own endpoint. ## Why it matters If a generated client has `Task` instead of `Task<FlightStatus>`, or a downstream tool has to invent an operation name because there is no `operationId`, the fix is in endpoint metadata, not in the document. The older `WithOpenApi()` extension is not needed for any of this; it is obsolete in .NET 10.

  • Why does a generated client get an untyped 200 for an endpoint that clearly returns a FlightStatus?
    The handler is declared to return `IResult`, and ApiExplorer treats `IResult` like `void` because `Results.Ok(...)` picks the body at run time. The document therefore has a 200 with no schema. Declare it with `.Produces<FlightStatus>()`, or change the declared return type so the type is visible.
  • Does a /// <response code="404"> XML comment add a 404 to the .NET 10 document?
    No. The XML-comment generator only adds a description to a response that metadata already declares. Without `Produces(404)`, `ProducesProblem(404)` or `[ProducesResponseType(404)]`, the 404 is not in the document and the comment has nothing to describe.
  • Where does the operationId come from on a controller action?
    The service uses the attribute route's `Name`, for example `[HttpGet("{id}", Name = "GetFlightStatus")]`, and falls back to `IEndpointNameMetadata`. With neither, the operation has no `operationId` and downstream tools invent one.

  • The generator reads the handler body, so Results.Ok(flight) documents the FlightStatus schema.
  • WithSummary sets the operationId, so the summary text must be unique across the API.
  • A /// <response code="404"> comment alone adds a 404 response to the document.
  • WithOpenApi() is still required in .NET 10 for WithSummary and Produces to appear.
  • AddControllers does not register ApiExplorer, so controllers are missing from the document.

Assumes ASP.NET Core 10: XML-comment support and the Description property on [ProducesResponseType] are new in 10, and WithOpenApi is obsolete (ASPDEPR002).