Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 2 · Lesson 18 · 5 min read

ASP.NET Core OpenAPI and Swagger Setup

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Typed, Documented Endpoint with a Bearer Scheme
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Generate an OpenAPI document from a .NET API, enrich it with accurate response types and metadata, choose an explorer UI for development, and decide deliberately what documentation is exposed in production given that it doubles as a map of your attack surface.

Concept Explanation

OpenAPI is a language-neutral, machine-readable description of an HTTP API: its paths, operations, parameters, request and response schemas, and security requirements. It is the successor to the Swagger specification and is maintained by the OpenAPI Initiative under the Linux Foundation. A description like this serves several audiences at once. Humans get interactive documentation, testers get a checklist of operations, and, most valuable for a full-stack developer, tools can generate a typed TypeScript client from it, so the React code and the .NET server cannot silently drift apart. You will do exactly that on Day 30.

In .NET, the Microsoft.AspNetCore.OpenApi package builds the document from the endpoints you have already written. You register it with AddOpenApi, expose the JSON with MapOpenApi, and the generator reads route templates, parameter types, and the return types of your handlers. It produces better documents when handlers use TypedResults and declare their responses, because a handler returning Results.Ok with no type gives the generator nothing to describe. Metadata methods such as WithSummary, WithDescription, and Produces refine the output, and document transformers let you add global information like servers and security schemes. Current versions support OpenAPI 3.1.

The document is data, and a UI is just a viewer. Historically Swashbuckle supplied both the generator and the Swagger UI, and older templates included it by default. Newer templates use the built-in generator, and you choose a viewer separately: Swagger UI, Scalar, or ReDoc are common. Any of them can send test requests, so configure the security scheme in the document so testers can paste a token and call protected endpoints, and give the viewer a dedicated test client registration rather than reusing a production one.

The security angle is that documentation is reconnaissance. A complete OpenAPI file lists every endpoint, parameter name, and data shape, including internal or administrative operations, and hands it to anyone who can reach the URL. The OWASP API Security Top 10 calls out improper inventory management, which includes exposed documentation, forgotten old versions, and debug endpoints, as a top risk. The sensible defaults are to serve the interactive documentation only in development and staging, to protect it behind authentication if it must exist in production, and to exclude internal endpoints from the public document. Obscurity is not protection, so real access control must never depend on hiding the docs, but there is no reason to volunteer a map.

ConcernTool or settingNote
Generate the documentAddOpenApi and MapOpenApiBuilt in, no third-party package required
Describe responses accuratelyTypedResults, Produces, ProducesProblemUntyped Results give an empty schema
Human-friendly explorerSwagger UI, Scalar or ReDocViewer is separate from the generator
Client generationopenapi-typescript, NSwagConsumes the JSON document
Auth in the explorerSecurity scheme via document transformerUse a dedicated test client
Production exposureConditional registration, or authenticationTreat the document as an attack map

Worked Example: A Typed, Documented Endpoint with a Bearer Scheme

The snippet registers OpenAPI, adds a bearer security scheme through a transformer, documents an endpoint's responses precisely, and exposes the explorer only outside production.

C#
builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer((document, context, ct) =>
    {
        document.Info.Title = "Notes API";
        document.Info.Version = "v1";
        document.Components ??= new();
        document.Components.SecuritySchemes["Bearer"] = new OpenApiSecurityScheme
        {
            Type = SecuritySchemeType.Http,
            Scheme = "bearer",
            BearerFormat = "JWT"
        };
        return Task.CompletedTask;
    });
});

var app = builder.Build();

if (!app.Environment.IsProduction())
{
    app.MapOpenApi();                               // serves /openapi/v1.json
    app.MapScalarApiReference();                    // interactive explorer (Scalar.AspNetCore package)
}

app.MapGet("/api/notes/{id:int}", GetNote)
   .WithName("GetNote")
   .WithSummary("Get a single note by id")
   .WithDescription("Returns 404 when the note does not exist or belongs to another user.")
   .RequireAuthorization();

static async Task<Results<Ok<NoteDto>, NotFound>> GetNote(int id, INoteStore store)
{
    var note = await store.FindAsync(id);
    return note is null ? TypedResults.NotFound() : TypedResults.Ok(NoteDto.From(note));
}

Because GetNote returns a Results union of Ok of NoteDto and NotFound, the generated document lists both responses with their schemas automatically. That accuracy is what allows a client generator to produce a function returning a NoteDto or a well-typed not found result.

Endpoints declared with TypedResults produce an OpenAPI document. It feeds a development-only explorer and a generated TypeScript client, and becomes an attack map if exposed in production.
Endpoints declared with TypedResults produce an OpenAPI document. It feeds a development-only explorer and a generated TypeScript client, and becomes an attack map if exposed in production.

Real-World Examples

  • The OpenAPI Initiative, part of the Linux Foundation, publishes the specification, and version 3.1, released in February 2021, aligned its schema language with JSON Schema. Stripe, GitHub, and many other large providers publish OpenAPI descriptions of their APIs, and entire ecosystems of client generators, mock servers, and testing tools consume them.
  • The OWASP API Security Top 10 2023 lists Improper Inventory Management as API9, covering exposed documentation endpoints, old API versions still running, and debug hosts. Unprotected Swagger interfaces on production systems are routinely found during security assessments, and they let testers enumerate and exercise every operation without any prior knowledge of the application.
Key TakeawaysGenerate an OpenAPI document from your ASP.NET Core endpoints, and describe responses with TypedResults so the schema stays accurate. Use it to generate a typed client for React. Serve the documentation viewer only in non-production environments or behind authentication, because the document is a complete map of what an attacker can call.

Review Questions & Answers

The generator infers response schemas from the declared return types, and an untyped result exposes nothing about the shape of the body. The operation appears with an empty or generic response, so client generators produce loosely typed code. Using TypedResults or Produces declarations gives the generator the concrete types it needs.

Tooling can generate TypeScript types and a client from the document, so the client's understanding of routes, parameters, and payloads comes from the server rather than being written by hand. When a server field changes, regenerating the client makes the compiler flag every affected call in the React code. Without that step, mismatches are discovered at runtime.

The document and explorer list every endpoint, parameter, and schema, including internal ones, giving attackers a free and complete inventory and a convenient way to send test requests. Security must not depend on secrecy, but reducing needless disclosure removes an easy first step. Restrict it to non-production environments or protect it with authentication.

It lets you modify the generated document programmatically, for example to set the title and version, add servers, or register the bearer security scheme. That keeps global metadata in code next to the API instead of hand-editing JSON. Operation and schema transformers similarly adjust individual endpoints or types.