ASP.NET Core cookbook · Beginner
Generate OpenAPI documents with Microsoft.AspNetCore.OpenApi
API consumers need an accurate, up-to-date contract with auth requirements and examples.
Approach
Call AddOpenApi() and MapOpenApi() to serve the document generated from your endpoints. Describe endpoints
with names, summaries and TypedResults, and add a document transformer for security schemes.
Solution
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi(options =>
{
options.AddDocumentTransformer((document, context, ct) =>
{
document.Info.Title = "Orders API";
document.Info.Version = "v1";
return Task.CompletedTask;
});
});
var app = builder.Build();
if (app.Environment.IsDevelopment() || app.Configuration.GetValue<bool>("Docs:Public"))
{
app.MapOpenApi(); // GET /openapi/v1.json
}
app.MapGet("/api/orders/{id:int}", (int id) => TypedResults.Ok(new OrderDto(id, "paid")))
.WithName("GetOrder")
.WithSummary("Get an order by ID")
.WithDescription("Returns 404 when the order doesn't exist or belongs to another customer.")
.Produces(StatusCodes.Status404NotFound);
app.Run();
public record OrderDto(int Id, string Status);
Pitfalls
- Publishing internal admin endpoints in the public document; exclude them with
.ExcludeFromDescription(). - Anonymous types in responses, which produce poorly named schemas; use records.
- Documentation that drifts because it's written by hand instead of generated.
Variations
- Generate the document at build time (
Microsoft.Extensions.ApiDescription.Server) and diff it in CI. - Serve a UI such as Scalar or Swagger UI pointing at
/openapi/v1.json.
Further reading: Generate OpenAPI documents
Reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/openapi/aspnetcore-openapi
More ASP.NET Core recipes
- Accept file uploads with size and type limits
- Add OpenTelemetry traces and metrics
- Apply EF Core migrations safely during deployment
- Bind and validate options at startup
- Cache responses with output caching and evict by tag
- Call external APIs with typed HttpClients and resilience
- Configure CORS for a browser front end
- Expose liveness and readiness health checks