OpenAPI & Scalar
ASP.NET Core can generate OpenAPI documents from endpoint metadata, while Scalar renders those documents as an interactive API reference for developers.
Overview
Microsoft.AspNetCore.OpenApi provides first-party document generation for Minimal APIs and controllers, including runtime endpoints, build-time generation, named documents, and transformers. In .NET 10 the generator emits an OpenAPI 3.1 document from routing, binding, typed results, validation, and explicit endpoint metadata. Scalar.AspNetCore is a separate UI integration that reads that portable document and renders searchable reference documentation and a request client. The UI is not the contract: operation identifiers, request schemas, success and failure responses, security requirements, examples, nullability, and version lifecycle must agree with runtime behavior. Contract tests and reviewed document diffs catch drift before it breaks generated clients, gateways, tests, or partners. Runtime JSON and interactive documentation also enlarge the discovery surface, so production exposure must be an explicit authenticated decision rather than a default copied from development.
What you will learn
- Explain the separate responsibilities of ASP.NET Core OpenAPI generation and Scalar presentation.
- Generate OpenAPI 3.1 documents from accurate endpoint metadata.
- Stabilize operation identifiers, schemas, responses, and document versions for consumers.
- Customize cross-cutting contract details with document, operation, and schema transformers.
- Test the generated JSON and interactive reference as deployment artifacts.
- Choose a safe production exposure policy for documents and request clients.
Prerequisites
- ASP.NET Core routing, Minimal APIs or controllers, model binding, and HTTP status codes.
- JSON schemas and the purpose of a machine-readable API contract.
- A .NET 10 SDK to run the dedicated catalog sample.
When to use OpenAPI & Scalar
Good fit
- Use first-party generation when ASP.NET Core endpoint metadata is the contract source.
- Use Scalar when developers need a searchable interactive reference over an existing OpenAPI document.
- Use named documents when versions or audiences have different lifecycle boundaries.
Choose another approach when
- Do not treat a polished UI as evidence that the underlying contract is accurate.
- Do not expose internal operations or browser-stored credentials through an unrestricted production reference.
- Do not make accidental operation ID or schema changes without compatibility review.
Key concepts
A language-neutral contract describing operations, paths, parameters, request bodies, responses, schemas, and security schemes.
Typed results, attributes, summaries, descriptions, and response declarations feed the generated operation definitions.
Transformers apply cross-cutting changes such as security schemes, branding metadata, or environment-specific server information.
Scalar consumes an OpenAPI URL and provides interactive, searchable documentation without generating the contract itself.
Stable endpoint names become operation identifiers used by client generators, tests, gateways, and consumer documentation.
Versioned documents, compatibility review, deprecation, generated artifacts, and consumer communication govern change.
Security schemes describe how callers authenticate, but runtime authentication and authorization still enforce access.
OpenAPI JSON and interactive request clients reveal capabilities and therefore need an intentional environment and access policy.
Architecture
ASP.NET Core endpoint metadata is assembled into an OpenAPI document, exposed as JSON, and consumed by Scalar or downstream client-generation tools.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The dedicated catalog sample generates a .NET 10 OpenAPI 3.1 document, gives each operation a stable name and complete response metadata, and maps Scalar only in Development. Integration tests inspect both the contract JSON and the rendered reference endpoint.
- 01Install deliberate dependencies
Reference Microsoft.AspNetCore.OpenApi, a patched Microsoft.OpenApi version, and Scalar.AspNetCore explicitly.
- 02Register a named document
Call AddOpenApi and decide whether one document or audience-specific documents match the API lifecycle.
- 03Describe operations
Use endpoint names, summaries, descriptions, tags, typed results, and validation metadata to describe behavior.
- 04Describe failures
Include validation, authorization, not-found, conflict, and other meaningful responses rather than documenting only 200.
- 05Apply transformers
Add shared information or security descriptions centrally while keeping business-specific metadata near endpoints.
- 06Control exposure
Map OpenAPI JSON and Scalar in Development or behind approved production authentication and authorization.
- 07Freeze the contract
Test required paths, operation IDs, schemas, and responses, and review document diffs in CI.
Code example
The app generates a first-party OpenAPI document and exposes Scalar only in development, while endpoint metadata improves the contract.
using Scalar.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi("v1");
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference(options =>
options.WithTitle("Orders API"));
}
app.MapGet("/api/orders/{id:guid}", (Guid id) =>
TypedResults.Ok(new OrderSummary(id, "Ready")))
.WithName("GetOrder")
.WithSummary("Gets one order by identifier")
.Produces<OrderSummary>(StatusCodes.Status200OK);
app.Run();
public sealed record OrderSummary(Guid Id, string Status);Testing strategy
Contract verification must compare generated metadata with real HTTP behavior.
- Parse the generated document and assert its OpenAPI version, required paths, methods, and stable operation IDs.
- Assert request and response schemas plus every significant status code.
- Exercise endpoints with integration tests so documented success and failure outcomes remain executable.
- Verify the Scalar route in the environments where it is intended to exist.
- Diff a normalized document or run a compatibility checker before publishing breaking changes.
Security considerations
Documentation is part of the API attack and credential-handling surface.
- Describe authentication schemes accurately without embedding tokens, client secrets, or real examples.
- Keep runtime authorization independent from the document and UI.
- Disable the document and Scalar in production unless discovery is intended and access is protected.
- Apply browser security headers and prevent shared machines from retaining privileged credentials.
- Filter internal-only endpoints from public documents and test the filter.
Performance and scalability
Generation is usually inexpensive, but large documents and interactive clients still consume startup, bandwidth, and browser resources.
- Generate once per document and avoid request-dependent expensive transformers.
- Split genuinely independent audiences or versions instead of shipping one unbounded contract.
- Cache immutable published documents with a versioned URL where appropriate.
- Measure generation and UI load time after adding large schemas or examples.
Deployment and operations
The document, UI, gateway import, and generated clients must all refer to the intended release contract.
- Set the environment explicitly and verify whether document routes exist after deployment.
- Publish the generated document as a versioned CI artifact for review and downstream tooling.
- Use correct external server URLs when proxies or gateways change the public origin.
- Run contract tests against the release build and smoke-test JSON and Scalar routes.
- Coordinate breaking changes with version and deprecation policy rather than silently replacing a document.
Common problems and fixes
An endpoint is missing from the document.
Likely cause: It was excluded, lacks discoverable metadata, or belongs to another named document.
Fix: Inspect routing and document selection metadata, then assert the expected path in a contract test.
A response schema or status is wrong.
Likely cause: Runtime branches and typed or explicit response metadata disagree.
Fix: Use typed results or Produces metadata for every material outcome and add matching HTTP tests.
Operation IDs change unexpectedly.
Likely cause: Endpoint names were omitted or renamed during refactoring.
Fix: Assign stable consumer-facing names and test them as compatibility-sensitive identifiers.
Scalar loads but cannot fetch the contract.
Likely cause: The document route, base path, proxy, environment, or authorization policy differs from the UI configuration.
Fix: Open the JSON URL directly and align Scalar's document URL with the deployed route.
The production document reveals internal routes.
Likely cause: Development mapping or audience filtering was copied to production.
Fix: Disable exposure or require authorization and generate a reviewed public document.
A dependency audit reports Microsoft.OpenApi risk.
Likely cause: A vulnerable transitive or direct package version was resolved.
Fix: Pin a patched compatible version, restore, rebuild, and repeat direct and transitive vulnerability audit.
Best practices
- Treat the OpenAPI document as a tested contract and fail continuous integration when unintended breaking changes appear.
- Use typed results and explicit metadata so status codes, schemas, descriptions, and security requirements match actual behavior.
- Give operations stable names because generated clients consume them as identifiers.
- Document validation and error responses, not only the happy path.
- Version APIs deliberately and publish separate documents when consumers need stable lifecycle boundaries.
- Use transformers for coherent cross-cutting metadata rather than ad hoc edits.
- Publish a normalized document artifact and review compatibility diffs.
- Restrict or secure interactive documentation in production and never prefill real credentials or secrets in a browser-visible client.
Production checklist
- Every operation has a stable name, summary, inputs, success responses, and failure responses.
- Schemas match nullability, validation, formats, and runtime serialization.
- Security schemes describe the real authentication contract without containing secrets.
- Named documents and versions have owners, lifecycle, and compatibility policy.
- Generated JSON is parsed and contract-tested in CI.
- Breaking diffs require explicit review and consumer communication.
- OpenAPI and Scalar production exposure is disabled or authenticated intentionally.
- External URLs, proxy paths, document JSON, and Scalar are smoke-tested after deployment.
Common interview questions
What roles do Microsoft.AspNetCore.OpenApi and Scalar play?
The Microsoft package generates the OpenAPI document from ASP.NET Core metadata. Scalar consumes that document and renders an interactive reference; it does not replace accurate contract generation.
Why can generated documentation still be wrong?
Generation reflects available metadata. If response types, status codes, security requirements, or descriptions are missing or differ from runtime behavior, the generated contract will preserve those gaps.
How should API versioning relate to OpenAPI documents?
Each supported public API version should have a clear lifecycle and discoverable contract, commonly through separate named documents that client teams can pin and compare.
Why are operation IDs compatibility-sensitive?
Client generators often turn them into method names, so an accidental rename can break source compatibility even when the path still works.
Should Scalar be enabled in production?
Only when production discovery is intentional and protected. Many services keep both JSON and the interactive client development-only or publish a separately governed public contract.
What is a document transformer for?
It applies cross-cutting document changes such as shared metadata or security scheme descriptions without duplicating edits across endpoints.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
OpenAPI Scalar Catalog
A .NET 10 catalog API demonstrating first-party OpenAPI 3.1 generation, stable operation IDs, typed response metadata, development-only Scalar reference UI, and contract inspection tests.
- Run
dotnet run --project src/OpenApiScalarCatalog- Test
dotnet test OpenApiScalarCatalog.slnx