Swashbuckle.AspNetCore Documentation

Swagger tools for documenting API's built on ASP.NET Core

5,482 stars C# C# 1 file ยท ~31,670 tokens
RAW Doc

File: README.md

Swashbuckle.AspNetCore

NuGet
NuGet Downloads

Build status
Code coverage
OpenSSF Scorecard

Help Wanted

OpenAPI (Swagger) tooling for APIs built with ASP.NET Core.

Generate beautiful API documentation, including a UI to explore and test operations, directly from your application code.

In addition to its Swagger 2.0 and OpenAPI 3.0/3.1 generator, Swashbuckle.AspNetCore also provides
an embedded version of the awesome swagger-ui project that's powered by the generated OpenAPI JSON documents.
This means you can complement your API with living documentation that's always in sync with the latest code. Best of all, it
requires minimal coding and maintenance, allowing you to focus on building an awesome API.

But that's not all!

Once you have an API that can describe itself with a OpenAPI document, you've opened the treasure chest of OpenAPI-based
tools including a client generator that can be targeted to a wide range of popular platforms. See swagger-codegen
for more details.

[!IMPORTANT]
Version 10.0 of Swashbuckle.AspNetCore introduces breaking changes due to upgrading our dependency on Microsoft.OpenApi
to version 2.x.x to add support for generating OpenAPI 3.1 documents. Please see Migrating to Swashbuckle.AspNetCore v10 for more details.

Compatibility

Swashbuckle Version ASP.NET Core OpenAPI/Swagger Versions Microsoft.OpenApi swagger-ui Redoc
CI Swashbuckle.AspNetCore version >= 8.0.0 3.1, 3.0, 2.0 Microsoft.OpenApi version swagger-ui version Redoc version
Latest Swashbuckle.AspNetCore version >= 8.0.0 3.1, 3.0, 2.0 Microsoft.OpenApi version swagger-ui version Redoc version
Last v9 Swashbuckle.AspNetCore version 9.0.x, 8.0.x 3.0, 2.0 Microsoft.OpenApi version swagger-ui version Redoc version
Last v8 Swashbuckle.AspNetCore version 9.0.x, 8.0.x, 2.3.x 3.0, 2.0 Microsoft.OpenApi version swagger-ui version Redoc version

Getting Started

First install the kitchen-sink NuGet package into your ASP.NET Core application:

terminal
dotnet add package Swashbuckle.AspNetCore

Next, register the OpenAPI (Swagger) generator in your application's startup path, defining one or more OpenAPI documents. For example:

cs
using Microsoft.OpenApi;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMvc();

builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});

var app = builder.Build();

app.UseSwagger();

app.Run();

snippet source | anchor

Ensure your API endpoints and any parameters are decorated with [Http*] and [From*] attributes, where appropriate.

cs
[HttpPost]
public void CreateProduct([FromBody] Product product)
{
    // Implementation goes here
}

[HttpGet]
public IEnumerable SearchProducts([FromQuery] string keywords)
{
    // Implementation goes here
    return [];
}

snippet source | anchor

[!NOTE]
If you omit the explicit parameter bindings, the generator will describe them as "query" parameters by default.

Then, expose the OpenAPI JSON document endpoint(s) using one of following methods:

  • Add endpoints if you're using endpoint-based routing:

cs
// Your own endpoints go here, and then...
app.MapSwagger();

snippet source | anchor

  • Adding the OpenAPI middleware:

cs
app.UseSwagger();

snippet source | anchor

At this point, you can launch your application and view the generated OpenAPI document at /swagger/v1/swagger.json.

Finally, you can optionally add the swagger-ui middleware to expose interactive documentation, specifying the OpenAPI document(s) to power it from:

cs
app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("v1/swagger.json", "My API V1");
});

snippet source | anchor

Now you can restart your application and view the auto-generated, interactive documentation at /swagger.

System.Text.Json (STJ) vs Newtonsoft.Json (Json.NET)

In versions of Swashbuckle.AspNetCore prior to 5.0.0, Swashbuckle.AspNetCore would generate Schemas (descriptions of the data types exposed by an API) based
on the behavior of the Newtonsoft.Json serializer. This made sense because that was the serializer that shipped with ASP.NET Core
at the time. However, since ASP.NET Core 3.0, ASP.NET Core introduces a new serializer, System.Text.Json (STJ) out-of-the-box.

If you want to use Newtonsoft.Json instead, you must install a separate package and explicitly opt-in. By default Swashbuckle.AspNetCore will assume
that you're using the System.Text.Json serializer and generate schemas based on its behavior. If you're using Newtonsoft.Json, then you'll need to install a
separate Swashbuckle.AspNetCore package, Swashbuckle.AspNetCore.Newtonsoft to explicitly opt-in.

Below is an example of how to do this for ASP.NET Core MVC:

terminal
dotnet add package Swashbuckle.AspNetCore.Newtonsoft

cs
services.AddMvc();

services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});

services.AddSwaggerGenNewtonsoftSupport();

snippet source | anchor

Swashbuckle, ApiExplorer, and Routing

Swashbuckle relies heavily on ApiExplorer, the API metadata layer that ships with ASP.NET Core. If you're using the AddMvc(...)
helper methods to bootstrap the MVC stack, then API Explorer will be automatically registered and Swashbuckle.AspNetCore should work without issue.

However, if you're using AddMvcCore(...) for a more paired-down MVC stack, you'll need to explicitly add the API Explorer services:

cs
services.AddMvcCore()
        .AddApiExplorer();

snippet source | anchor

Additionally, if you are using conventional routing (as opposed to attribute routing), any controllers and the actions on those
controllers that use conventional routing will not be represented in API Explorer, which means Swashbuckle won't be able to find those controllers and
generate OpenAPI operations for them.

For instance:

cs
app.UseMvc(routes =>
{
    // SwaggerGen won't find controllers that are routed via this technique.
    routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

snippet source | anchor

You must use attribute routing for any controllers that you want represented in your OpenAPI document(s):

cs
[Route("example")]
public class ExampleController : Controller
{
    [HttpGet("")]
    public IActionResult DoStuff()
    {
        // Your implementation
        return Empty;
    }
}

snippet source | anchor

Refer to the ASP.NET Core MVC routing documentation for more information.

Components

Swashbuckle.AspNetCore consists of multiple components that can be used together or individually depending on your needs.

At its core, there's an OpenAPI generator, middleware to expose OpenAPI (Swagger) documentation as JSON endpoints, and a
packaged version of the swagger-ui. These three packages can be installed with the Swashbuckle.AspNetCore
"metapackage" and will work together (see Getting Started) to provide API documentation that is automatically generated from your code.

Additionally, there are add-on packages (CLI tools, an alternate UI using Redoc etc.) that you can install and configure as needed.

"Core" Packages

Package NuGet Description
Swashbuckle.AspNetCore.Swagger Exposes OpenAPI JSON endpoints. It expects an implementation of ISwaggerProvider to be registered in the DI container, which it queries to retrieve OpenApiDocument instance(s) that are then exposed as serialized JSON.
Swashbuckle.AspNetCore.SwaggerGen Injects an implementation of ISwaggerProvider that can be used by the above component. This particular implementation generates OpenApiDocument instance(s) from your application endpoints (controllers, minimal endpoints etc.).
Swashbuckle.AspNetCore.SwaggerUI Exposes an embedded version of swagger-ui. You specify the API endpoints where it can obtain OpenAPI documents from, and it uses them to power interactive documentation for your API.

Additional Packages

Package NuGet Description
Swashbuckle.AspNetCore.Annotations Includes a set of custom attributes that can be applied to controllers/endpoints, actions and models to enrich the generated documentation.
Swashbuckle.AspNetCore.Cli Provides a command line interface (CLI) for retrieving OpenAPI documents directly from an application start-up assembly and then writing to a file.
Swashbuckle.AspNetCore.ReDoc Exposes an embedded version of the Redoc UI (an alternative to swagger-ui).

Community Packages

These packages are provided by the .NET open-source community.

Package NuGet Description
Swashbuckle.AspNetCore.Filters Some useful Swashbuckle.AspNetCore filters which add additional documentation, e.g. request and response examples, authorization information, etc. See its README for more details.
Unchase.Swashbuckle.AspNetCore.Extensions Some useful extensions (filters), which add additional documentation, e.g. hide PathItems for unaccepted roles, fix enumerations for client code generation, etc. See its README for more details.
MicroElements.Swashbuckle.FluentValidation Use FluentValidation rules instead of ComponentModel attributes to augment generated OpenAPI schemas.
MMLib.SwaggerForOcelot Aggregate documentations over microservices directly on Ocelot API Gateway.

Configuration and Customization

The steps described above will get you up and running with minimal set up. However, Swashbuckle.AspNetCore offers a lot of flexibility to customize as you see fit.

Check out the table below for the full list of possible configuration options.

Component Configuration and Customization
Swashbuckle.AspNetCore.Swagger Change the Path for OpenAPI JSON Endpoints
Modify OpenAPI with Request Context
Serialize OpenAPI JSON in the 3.1 format
Serialize Swagger JSON in the 2.0 format
Working with Virtual Directories and Reverse Proxies
Customizing how the OpenAPI document is serialized
Swashbuckle.AspNetCore.SwaggerGen Assign Explicit OperationIds
List Operations Responses
Flag Required Parameters and Schema Properties
Handle Forms and File Uploads
Handle File Downloads
Include Descriptions from XML Comments
Provide Global API Metadata
Generate Multiple OpenAPI Documents
Omit Obsolete Operations and/or Schema Properties
Omit Arbitrary Operations
Customize Operation Tags (e.g. for UI Grouping)
Change Operation Sort Order (e.g. for UI Sorting)
Customize Schema Ids
Override Schema for Specific Types
Extend Generator with Operation, Schema & Document Filters
Add Security Definitions and Requirements
Add Security Definitions and Requirements for Bearer auth
Inheritance and Polymorphism
Swashbuckle.AspNetCore.SwaggerUI Change Relative Path to the UI
Change Document Title
Change CSS or JS Paths
List Multiple OpenAPI Documents
Apply swagger-ui Parameters
Inject Custom JavaScript
Inject Custom CSS
Customize index.html
Enable OAuth2.0 Flows
Use client-side request and response interceptors
Swashbuckle.AspNetCore.Annotations Install and Enable Annotations
Enrich Operation Metadata
Enrich Response Metadata
Enrich Parameter Metadata
Enrich RequestBody Metadata
Enrich Schema Metadata
Apply Schema Filters to Specific Types
Add Tag Metadata
Swashbuckle.AspNetCore.Cli Retrieve OpenAPI Directly from a Startup Assembly
Use the CLI Tool with a Custom Host Configuration
Swashbuckle.AspNetCore.ReDoc Change Relative Path to the UI
Change Document Title
Apply Redoc Parameters
Inject Custom CSS
Customize index.html

File: docs/configure-and-customize-annotations.md

Configuration and Customization of `Swashbuckle.AspNetCore.Annotations`

Install and Enable Annotations

First install the following NuGet package into your ASP.NET Core application.

terminal
dotnet add package Swashbuckle.AspNetCore.Annotations

Next in your application's startup path, enable annotations within the Swagger configuration callback:

cs
services.AddSwaggerGen(options =>
{
    // Other setup, then...
    options.EnableAnnotations();
});

snippet source | anchor

Enrich Operation Metadata

Once annotations have been enabled, you can enrich the generated Operation metadata by decorating actions with [SwaggerOperation].

cs
[HttpPost]
[SwaggerOperation(
    Summary = "Creates a new product",
    Description = "Requires admin privileges",
    OperationId = "CreateProduct",
    Tags = ["Purchase", "Products"]
)]
public IActionResult Create([FromBody] Product product)
{
    //...
    return Ok();
}

snippet source | anchor

Enrich Response Metadata

ASP.NET Core provides the ProducesResponseTypeAttribute for listing the different responses that
can be returned by an action. These attributes can be combined with XML comments, as described
further here, to
include human-friendly descriptions with each response in the generated document. If you'd prefer
to do all of this with a single attribute, and avoid the use of XML comments, you can use one or more [SwaggerResponse] instead:

cs
[HttpPost]
[SwaggerResponse(201, "The product was created", typeof(Product))]
[SwaggerResponse(400, "The product data is invalid")]
public IActionResult Post([FromBody] Product product)
{
    //...
    return Created();
}

snippet source | anchor

Enrich Parameter Metadata

You can annotate path, query or header-bound parameters or properties (i.e. decorated with [FromRoute], [FromQuery]
or [FromHeader]) with a SwaggerParameterAttribute to enrich the corresponding Parameter metadata that's generated by Swashbuckle.AspNetCore:

cs
[HttpGet]
public IActionResult GetProducts(
    [FromQuery, SwaggerParameter("Search keywords", Required = true)] string keywords)
{
    //...
    return Ok();
}

snippet source | anchor

Enrich RequestBody Metadata

You can annotate body-bound parameters or properties (i.e. decorated with [FromBody]) with [SwaggerRequestBody] to enrich
the corresponding RequestBody metadata that's generated by Swashbuckle.AspNetCore:

cs
[HttpPost]
public IActionResult SubmitProduct(
    [FromBody, SwaggerRequestBody("The product payload", Required = true)] Product product)
{
    //...
    return Created();
}

snippet source | anchor

Enrich Schema Metadata

You can annotate classes or properties with [SwaggerSchema] to enrich the corresponding Schema metadata that's generated by Swashbuckle.AspNetCore:

cs
[SwaggerSchema(Required = ["Description"])]
public class Product
{
    [SwaggerSchema("The product identifier", ReadOnly = true)]
    public int Id { get; set; }

    [SwaggerSchema("The product description")]
    public string Description { get; set; } = string.Empty;

    [SwaggerSchema("The date it was created", Format = "date")]
    public DateTime DateCreated { get; set; }
}

snippet source | anchor

[!NOTE]
In OpenAPI, serialized objects and contained properties are represented as Schema instances, hence why this annotation can
be applied to both classes and properties. Also, required properties are specified as an array of property names on the top-level schema
as opposed to a flag on each individual property.

Apply Schema Filters to Specific Types

The Swashbuckle.AspNetCore.SwaggerGen NuGet package provides several extension points, including
Schema Filters for
customizing all generated Schemas. However, there may be cases where it's preferable to apply a filter to a specific
Schema. For example, if you'd like to include an example for a specific type in your API. This can be done by decorating the
type with [SwaggerSchemaFilter]:

๐Ÿ“ Item.cs

cs
[SwaggerSchemaFilter(typeof(ItemSchemaFilter))]
public class Item
{
    //...
}

snippet source | anchor

๐Ÿ“ ItemSchemaFilter.cs

cs
public class ItemSchemaFilter : ISchemaFilter
{
    public void Apply(IOpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema is OpenApiSchema concrete)
        {
            concrete.Example = new JsonObject
            {
                ["Id"] = 1,
                ["Description"] = "An awesome item"
            };
        }
    }
}

snippet source | anchor

Add Tag Metadata

By default, the OpenAPI generator will tag all operations with the controller name for MVC applications. This tag is then
used to drive the operation groupings in swagger-ui. If you'd like to provide
a description for each of these groups, you can do so by adding metadata for each controller name tag using [SwaggerTag]:

cs
[SwaggerTag("Create, read, update and delete Items")]
public class ItemsController
{
    //...
}

snippet source | anchor

[!NOTE]
This will add the above description specifically to the tag named Items. Therefore, you should avoid using this attribute
if you're tagging Operations with something other than the controller name - e.g. if you're customizing the tagging behavior with TagActionsBy.

List Known Subtypes for Inheritance and Polymorphism

If you want to use Swashbuckle's inheritance and/or polymorphism behavior,
you can use annotations to explicitly indicate the "known" subtypes for a given base type. This will override the default selector function,
which selects all subtypes in the same assembly as the base type, and therefore needs to be explicitly enabled when you enable Annotations:

๐Ÿ“ Startup.cs

cs
services.AddSwaggerGen(options =>
{
    options.EnableAnnotations(enableAnnotationsForInheritance: true, enableAnnotationsForPolymorphism: true);
});

snippet source | anchor

๐Ÿ“ Shape.cs

cs
[JsonDerivedType(typeof(Rectangle))]
[JsonDerivedType(typeof(Circle))]
public abstract class Shape
{
}

snippet source | anchor

Enrich Polymorphic Base Classes with Discriminator Metadata

If you're using annotations to explicitly indicate the "known" subtypes for a polymorphic base type, you can combine
[JsonPolymorphic] with [JsonDerivedType] to provide additional metadata about the "discriminator" property, which will
then be incorporated into the generated schema definition:

๐Ÿ“ Startup.cs

cs
services.AddSwaggerGen(options =>
{
    options.EnableAnnotations(enableAnnotationsForInheritance: true, enableAnnotationsForPolymorphism: true);
});

snippet source | anchor

๐Ÿ“ ShapeWithDiscriminator.cs

cs
[JsonPolymorphic(TypeDiscriminatorPropertyName = "shapeType")]
[JsonDerivedType(typeof(Rectangle), "rectangle")]
[JsonDerivedType(typeof(Circle), "circle")]
public abstract class ShapeWithDiscriminator
{
    // Avoid using a JsonPolymorphicAttribute.TypeDiscriminatorPropertyName
    // that conflicts with a property in your type hierarchy.
    // Related issue: https://github.com/dotnet/runtime/issues/72170
}

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum ShapeType
{
    Circle,
    Rectangle
}

snippet source | anchor

This indicates that the corresponding payload will have a "shapeType" property to discriminate between subtypes, and that property
will have a value of "rectangle" if the payload represents a Rectangle type and a value of "circle" if it represents a Circle type.
This detail will be described in the generated schema definition as follows:

yaml
schema: {
  oneOf: [
    {
      $ref: "#/components/schemas/Rectangle"
    },
    {
      $ref: "#/components/schemas/Circle"
    },
  ],
  discriminator: {
    propertyName: shapeType,
    mapping: {
      rectangle: "#/components/schemas/Rectangle",
      circle: "#/components/schemas/Circle",
    }
  }
}

File: docs/configure-and-customize-cli.md

Configuration and Customization of `Swashbuckle.AspNetCore.Cli`

Retrieve OpenAPI Directly from a Startup Assembly

Once your application has been set up with Swashbuckle.AspNetCore (see Getting Started), you can
use the Swashbuckle.OpenAPI CLI tool to retrieve OpenAPI JSON documents directly from your application's startup assembly, and write
it to a file. This can be useful if you want to incorporate OpenAPI generation into a CI/CD process, or if you want to serve
it from static file at run-time.

It's packaged as a .NET Tool that can be installed and used via the .NET SDK.

[!WARNING]
The tool needs to load your Startup DLL and its dependencies at runtime. Therefore, you should use a version of the dotnet CLI
that is compatible with your application. For example, if your app targets net10.0, then you should use version 10.0.xxx of the
.NET SDK to run the CLI tool.

Using the tool with the .NET SDK

Install as a Global Tool

To install as a global tool:

terminal
dotnet tool install -g Swashbuckle.AspNetCore.Cli

Install as a local tool

  1. In your solution root directory, create a tool manifest file:

    terminal
    dotnet new tool-manifest
  2. Install as a local tool

    terminal
    dotnet tool install Swashbuckle.AspNetCore.Cli

Usage

  1. Verify that the tool was installed correctly

    termainal
    swagger tofile --help
  2. Generate an OpenAPI document from your application's startup assembly

    terminal
    swagger tofile --output [output] [startupassembly] [swaggerdoc]

    Placeholders and their meaning:

    • [output]: the relative path where the OpenAPI JSON document will be output to;
    • [startupassembly]: the relative path to your application's startup assembly;
    • [swaggerdoc]: the name of the OpenAPI document you want to generate, as configured in your application.

Use the CLI Tool with a Custom Host Configuration

By default, the tool will execute in the context of a "default" web host. However, in some cases you may want to
bring your own host environment, for example if you've configured a custom DI container such as Autofac. For this
scenario, the Swashbuckle CLI tool exposes a convention-based hook for your application.

That is, if your application contains a class that meets either of the following naming conventions, then that class
will be used to provide a host for the CLI tool to run in.

  • public class SwaggerHostFactory, containing a public static method called CreateHost with return type IHost
  • public class SwaggerWebHostFactory, containing a public static method called CreateWebHost with return type IWebHost

For example, the following class could be used to leverage the same host configuration as your application:

cs
public class SwaggerHostFactory
{
    public static IHost CreateHost()
        => MyApplication.CreateHostBuilder([]).Build();
}

snippet source | anchor


File: docs/configure-and-customize-redoc.md

Configuration and Customization of `Swashbuckle.AspNetCore.ReDoc`

Change Relative Path to the UI

By default, the Redoc UI will be exposed at /api-docs. If necessary, you can alter this when enabling the Redoc middleware:

cs
app.UseReDoc(options =>
{
    options.RoutePrefix = "docs";
});

snippet source | anchor

Change Document Title

By default, the Redoc UI will have a generic document title. You can alter this when enabling the Redoc middleware:

cs
app.UseReDoc(options =>
{
    options.DocumentTitle = "My API Docs";
});

snippet source | anchor

Apply Redoc Parameters

Redoc ships with its own set of configuration parameters, all described in the Redoc documentation.
In Swashbuckle.AspNetCore, most of these are surfaced through the Redoc middleware options:

cs
app.UseReDoc(options =>
{
    options.SpecUrl("/v1/swagger.json");
    options.EnableUntrustedSpec();
    options.ScrollYOffset(10);
    options.HideHostname();
    options.HideDownloadButton();
    options.ExpandResponses("200,201");
    options.RequiredPropsFirst();
    options.NoAutoAuth();
    options.PathInMiddlePanel();
    options.HideLoading();
    options.NativeScrollbars();
    options.DisableSearch();
    options.OnlyRequiredInSamples();
    options.SortPropsAlphabetically();
});

snippet source | anchor

[!NOTE]
Using options.SpecUrl("/v1/swagger.json") multiple times within the same UseReDoc(...) will not add multiple URLs.

Inject Custom CSS

To tweak the look and feel, you can inject additional CSS stylesheets by adding them to your wwwroot folder and specifying
the relative paths in the middleware options:

cs
app.UseReDoc(options =>
{
    options.InjectStylesheet("/redoc/custom.css");
});

snippet source | anchor

It is also possible to modify the theme by using the AdditionalItems property. More information can be found
in the Redoc documentation.

cs
app.UseReDoc(options =>
{
    options.ConfigObject.AdditionalItems = new Dictionary<string, object>
    {
        // Configured additional options
    };
});

snippet source | anchor

Customize index.html

To customize the UI beyond the basic options listed above, you can provide your own version of the Redoc index.html page:

cs
app.UseReDoc(options =>
{
    options.IndexStream = () => typeof(Program).Assembly
        .GetManifestResourceStream("CustomIndex.ReDoc.index.html"); // Requires file to be added as an embedded resource
});

snippet source | anchor

xml

[!TIP]
To get started, you should base your custom index.html on the default version.

Use `MapReDoc` with endpoint routing

MapReDoc is an endpoint-routing alternative to UseReDoc. The options API is the same, so all customization examples on this page also apply when using MapReDoc.

cs
app.MapReDoc();

snippet source | anchor

The main differences are:

  • UseReDoc adds middleware directly to the request pipeline and returns IApplicationBuilder.

  • MapReDoc maps ReDoc via endpoint routing and returns IEndpointConventionBuilder.

  • Because MapReDoc returns an endpoint convention builder, you can attach endpoint metadata/conventions (for example, authorization policies) directly to the mapped ReDoc endpoint.

cs
app.MapReDoc("redoc-auth")
   .RequireAuthorization(); // Remember to also add RequireAuthorization to MapSwagger

snippet source | anchor


File: docs/configure-and-customize-swagger.md

Configuration and Customization of `Swashbuckle.AspNetCore.Swagger`

Change the Path for OpenAPI JSON Endpoints

By default, OpenAPI (Swagger) JSON will be exposed at the following route - /swagger/{documentName}/swagger.json.
If necessary, you can change this when enabling the Swagger middleware.

[!IMPORTANT]
Custom routes must include the {documentName} parameter.

cs
app.UseSwagger(options =>
{
    options.RouteTemplate = "api-docs/{documentName}/swagger.json";
});

snippet source | anchor

[!NOTE]
If you're using the SwaggerUI middleware, you'll also need to update its configuration to reflect the new endpoints:

csharp
app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/api-docs/v1/swagger.json", "My API V1");
});

If you also need to update the relative path that the UI itself is available on, you'll need to follow the instructions
found in Change Relative Path to the UI.

Modify OpenAPI with Request Context

If you need to set some OpenAPI metadata based on the current request, you can configure a filter that's executed prior to serializing the document.

cs
app.UseSwagger(options =>
{
    options.PreSerializeFilters.Add((document, request) =>
    {
        document.Servers = [new OpenApiServer { Url = $"{request.Scheme}://{request.Host.Value}" }];
    });
});

snippet source | anchor

The OpenApiDocument and the current HttpRequest are both passed to the filter, which provides a lot of flexibility.
For example, you can add an explicit API server based on the Host header (as shown), or you could inspect session
information or an Authorization header and remove operations from the document based on user permissions.

Serialize OpenAPI in the 3.1 format

By default, Swashbuckle.AspNetCore will generate and expose OpenAPI JSON in version 3.0 of the specification.
However, if you wish to use the latest version of the OpenAPI specification, you can opt into version 3.1
format with the following option:

cs
app.UseSwagger(options =>
{
    options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_1;
});

snippet source | anchor

Serialize Swagger in the 2.0 format

By default, Swashbuckle will generate and expose OpenAPI JSON in version 3.0 of the specification, officially called the
OpenAPI Specification. However, to support backwards compatibility, you can opt to continue exposing it in the Swagger 2.0
format with the following option:

cs
app.UseSwagger(options =>
{
    options.OpenApiVersion = OpenApiSpecVersion.OpenApi2_0;
});

snippet source | anchor

Working with Virtual Directories and Reverse Proxies

Virtual directories and reverse proxies can cause issues for applications that generate links and redirects, particularly
if the app returns absolute URLs based on the Host header and other information from the current request. To avoid these
issues, Swashbuckle.AspNetCore uses relative URLs where possible, and encourages their use when configuring the SwaggerUI
and ReDoc middleware.

For example, to wire up the SwaggerUI middleware, you provide the URL to one or more OpenAPI documents. This is the URL
that swagger-ui, a client-side application, will call to retrieve your API metadata. To ensure this works behind
virtual directories and reverse proxies, you should express this relative to the RoutePrefix of swagger-ui itself:

cs
app.UseSwaggerUI(options =>
{
    options.RoutePrefix = "swagger";
    options.SwaggerEndpoint("v1/swagger.json", "My API V1");
});

snippet source | anchor

Customizing how the OpenAPI document is serialized

By default, Swashbuckle.AspNetCore will serialize the OpenAPI document using the Serialize* methods on the OpenAPI document object. If a
customized serialization is desired, it is possible to create a custom document serializer that implements the ISwaggerDocumentSerializer interface.
This can be set on the SwaggerOptions in the service collection using ConfigureSwagger():

cs
services.ConfigureSwagger(options =>
{
    options.SetCustomDocumentSerializer<CustomDocumentSerializer>();
});

snippet source | anchor

[!NOTE]
If you plan on using the command line tool to generate OpenAPI specification files, this must be done on the service
collection using ConfigureSwagger().

When the command line tool is not used, it can also be done on the application host:

cs
app.UseSwagger(options =>
{
    options.SetCustomDocumentSerializer<CustomDocumentSerializer>();
});

snippet source | anchor


File: docs/configure-and-customize-swaggergen.md

Configuration and Customization of `Swashbuckle.AspNetCore.SwaggerGen`

Assign Explicit OperationIds

In OpenAPI, operations may be assigned an operationId. This ID must be unique among all operations described in the API.
Tools and libraries (e.g. client generators) may use the operationId to uniquely identify an operation, therefore, it is
recommended to follow common programming naming conventions.

Auto-generating an ID that matches these requirements, while also providing a name that would be meaningful in client libraries,
is a non-trivial task and thus Swashbuckle.AspNetCore omits the operationId by default. However, if necessary, you can assign
operationIds by decorating individual routes or by providing a custom strategy.

Option 1: Decorate routes with a `Name` property

cs
// operationId = "GetProductById"
[HttpGet("{id}", Name = "GetProductById")]
public IActionResult Get(int id)
{
    // ...
    return Ok();
}

snippet source | anchor

Option 2: Provide a custom strategy

๐Ÿ“ Startup.cs

cs
services.AddSwaggerGen(options =>
{
    // Other configuration...

    // Use method name as operationId
    options.CustomOperationIds(apiDescription =>
    {
        return apiDescription.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null;
    });
});

snippet source | anchor

๐Ÿ“ ProductsController.cs

cs
// operationId = "GetProductById"
[HttpGet("/product/{id}")]
public IActionResult GetProductById(int id)
{
    // ...
    return Ok();
}

snippet source | anchor

[!NOTE]
With either approach, API authors are responsible for ensuring the uniqueness of operationIds across all operations.

List Operation Responses

By default, Swashbuckle.AspNetCore will generate an HTTP "200" response for each operation. If the endpoint returns a
response object, then this will be used to generate a schema for the response body. For example:

cs
[HttpPost("{id}")]
public Product GetById(int id)
{
    // ...
    return new Product();
}

snippet source | anchor

This endpoint will produce the following response metadata:

yaml
responses: {
  200: {
    content: {
      "application/json": {
        schema: {
          $ref: "#/components/schemas/Product"
        }
      }
    }
  }
}

Explicit Responses

If you need to specify a different status code and/or additional responses, or your MVC actions return IActionResult instead
of a response object, you can explicitly describe responses with [ProducesResponseType] which is part of ASP.NET Core. For example:

cs
[HttpPost("product/{id}")]
[ProducesResponseType(typeof(Product), 200)]
[ProducesResponseType(typeof(IDictionary<string, string>), 400)]
[ProducesResponseType(500)]
public IActionResult GetProductInfoById(int id)
{
    // ...
    return Ok();
}

snippet source | anchor

This endpoint will produce the following response metadata:

yaml
responses: {
  200: {
    content: {
      "application/json": {
        schema: {
          $ref: "#/components/schemas/Product"
        }
      }
    }
  },
  400: {
    content: {
      "application/json": {
        schema: {
          type: "object",
          additionalProperties: {
            type: "string"
          }
        }
      }
    }
  },
  500: {
    content: {}
  }
}

Flag Required Parameters and Schema Properties

In an OpenAPI document, you can flag parameters and schema properties that are required for a request. If a parameter
(top-level or property-based) is decorated with [BindRequired] or [Required], then Swashbuckle.AspNetCore will automatically
flag it as a required parameter in the generated OpenAPI document:

๐Ÿ“ ProductsController.cs

cs
public IActionResult Search([FromQuery, BindRequired] string keywords, [FromQuery] PagingOptions paging)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    // ...
    return Ok();
}

snippet source | anchor

๐Ÿ“ PagingOptions.cs

cs
public class PagingOptions
{
    [Required]
    public int PageNumber { get; set; }

    public int PageSize { get; set; }
}

snippet source | anchor

In addition to parameters, Swashbuckle.AspNetCore will also honor [Required] when used in a model that's bound to the request body.
In this case, the decorated properties will be flagged as required properties in the body description:

๐Ÿ“ ProductsController.cs

cs
public IActionResult CreateNewProduct([FromBody] NewProduct product)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    // ...
    return Created();
}

snippet source | anchor

๐Ÿ“ NewProduct.cs

cs
public class NewProduct
{
    [Required]
    public string Name { get; set; } = string.Empty;

    public string Description { get; set; } = string.Empty;
}

snippet source | anchor

Handle Forms and File Uploads

This MVC controller will accept two form field values and one named file upload from the same form:

cs
[HttpPost]
public void UploadFile([FromForm] string description, [FromForm] DateTime clientDate, IFormFile file)
{
    // ...
}

snippet source | anchor

[!IMPORTANT]
As per the ASP.NET Core documentation, you're not supposed to
decorate IFormFile parameters with the [FromForm] attribute as the binding source is automatically inferred from the type. In fact,
the inferred value is BindingSource.FormFile and if you apply the attribute it will be set to BindingSource.Form instead, which breaks
ApiExplorer, the metadata component that ships with ASP.NET Core and is heavily relied on by Swashbuckle.AspNetCore. One particular issue here is
that SwaggerUI will not treat the parameter as a file and so will not display a file upload button, if you do mistakenly include this attribute.

Handle File Downloads

[!IMPORTANT]
ApiExplorer (the ASP.NET Core metadata component that Swashbuckle.AspNetCore is built on) does not surface the FileResult types by
default and so you need to explicitly configure it to do so with [ProducesResponseType]:

cs
[HttpGet("download/{fileName}")]
[ProducesResponseType(typeof(FileStreamResult), StatusCodes.Status200OK, "image/jpeg")]
public FileStreamResult GetImage(string fileName)
{
    // ...
    return new FileStreamResult(Stream.Null, "image/jpeg");
}

snippet source | anchor

Include Descriptions from XML Comments

To enhance the generated docs with human-friendly descriptions, you can annotate endpoints and models with
XML Comments and configure Swashbuckle.AspNetCore
to include those comments into the generated OpenAPI document.

First open the Properties dialog for your project, click the "Build" tab and ensure that "XML documentation file" is checked, or add an
<GenerateDocumentationFile>true</GenerateDocumentationFile> element to a `` in your .csproj file. This
will produce a file containing all XML comments at build-time.

At this point, any classes or methods that are not annotated with XML comments will trigger a build warning. To suppress this,
enter the warning code 1591 into the "Suppress warnings" field in the Properties dialog or add <NoWarn>$(NoWarn);1591</NoWarn> to a
`` of your .csproj project file.

Next configure Swashbuckle.AspNetCore to incorporate the XML comments on file into the generated OpenAPI JSON:

cs
services.AddSwaggerGen(options =>
{
    options.SwaggerDoc(
        "v1",
        new OpenApiInfo
        {
            Title = "My API - V1",
            Version = "v1"
        }
    );

    options.IncludeXmlComments(Assembly.GetExecutingAssembly());
    // or options.IncludeXmlComments(typeof(MyController).Assembly));
});

snippet source | anchor

Next annotate your endpoints with summary, remarks, param and/or response tags as desired:

cs
/// 
/// Retrieves a specific product line by unique id
/// 
/// <remarks>Awesomeness!</remarks>
/// The product line id
/// <response code="200">Product line retrieved</response>
/// <response code="404">Product line not found</response>
/// <response code="500">Oops! Can't lookup your product line right now</response>
[HttpGet("product/{id}")]
[ProducesResponseType(typeof(ProductLine), 200)]
[ProducesResponseType(404)]
[ProducesResponseType(500)]
public ProductLine GetProductBySystemId(int id)
{
    // ...
    return new ProductLine();
}

snippet source | anchor

Then annotate your types with summary and example tags, other tags (remarks, para, etc.) are not supported:

cs
public class ProductLine
{
    /// 
    /// The name of the product
    /// 
    /// <example>Men's basketball shoes</example>
    public string Name { get; set; } = string.Empty;

    /// 
    /// Quantity left in stock
    /// 
    /// <example>10</example>
    public int AvailableStock { get; set; }

    /// 
    /// The sizes the product is available in
    /// 
    /// <example>["Small", "Medium", "Large"]</example>
    public List<string> Sizes { get; set; } = [];
}

snippet source | anchor

Finally, rebuild your project to update the XML Comments file and navigate to the OpenAPI JSON endpoint. Note how the descriptions are
mapped onto corresponding OpenAPI properties.

[!NOTE]
You can also provide OpenAPI schema descriptions by annotating your API models and their properties with `` tags. If you
have multiple XML comments files (e.g. separate libraries for controllers and models), you can invoke the IncludeXmlComments method
multiple times and they will all be merged into the generated OpenAPI document.

Provide Global API Metadata

In addition to "PathItems", "Operations" and "Responses", which Swashbuckle.AspNetCore generates for you, OpenAPI also supports
global metadata. For example, you can provide a full description for your API, terms
of service or even contact and licensing information:

cs
services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1",
        new OpenApiInfo
        {
            Title = "My API - V1",
            Version = "v1",
            Description = "A sample API to demo Swashbuckle",
            TermsOfService = new Uri("http://tempuri.org/terms"),
            Contact = new OpenApiContact
            {
                Name = "Joe Developer",
                Email = "[email protected]"
            },
            License = new OpenApiLicense
            {
                Name = "Apache 2.0",
                Url = new Uri("https://www.apache.org/licenses/LICENSE-2.0.html")
            }
        }
    );
});

snippet source | anchor

[!TIP]
Use IntelliSense to see what other members are available.

Generate Multiple OpenAPI Documents

With the setup described above, the generator will include all API operations in a single Swagger document. However, you can
create multiple documents if necessary. For example, you may want a separate document for each version of your API. To do this, start
by defining multiple Swagger documents in your application startup code:

cs
services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API - V1", Version = "v1" });
    options.SwaggerDoc("v2", new OpenApiInfo { Title = "My API - V2", Version = "v2" });
});

snippet source | anchor

[!NOTE]
Take note of the first argument to SwaggerDoc. It must be a URI-friendly name that uniquely identifies the document.
It's subsequently used to make up the path for requesting the corresponding Swagger JSON. For example, with the default
routing, the above documents will be available at /swagger/v1/swagger.json and /swagger/v2/swagger.json.

Next, you'll need to inform Swashbuckle which actions to include in each document. Although this can be customized (see below), by
default, the generator will use the ApiDescription.GroupName property, part of the built-in metadata layer that ships with
ASP.NET Core, to make this distinction. You can set this by decorating individual actions or by applying an application-wide convention.

Decorate Individual Actions

To include an action in a specific Swagger document, decorate it with [ApiExplorerSettings] and set GroupName to the corresponding
document name (case sensitive):

cs
[HttpPost]
[ApiExplorerSettings(GroupName = "v2")]
public void PostLine([FromBody] ProductLine product)
{
    // ...
}

snippet source | anchor

Assign Actions to Documents by Convention

To group by convention instead of decorating every action, you can apply a custom controller or action convention. For example, you
could wire up the following convention to assign actions to documents based on the controller namespace.

๐Ÿ“ ApiExplorerGroupPerVersionConvention.cs

cs
public class ApiExplorerGroupPerVersionConvention : IControllerModelConvention
{
    public void Apply(ControllerModel controller)
    {
        var controllerNamespace = controller.ControllerType.Namespace; // e.g. "Controllers.V1"
        var apiVersion = controllerNamespace?.Split('.').Last().ToLower();

        controller.ApiExplorer.GroupName = apiVersion;
    }
}

snippet source | anchor

๐Ÿ“ Startup.cs

cs
services.AddMvc(options =>
    options.Conventions.Add(new ApiExplorerGroupPerVersionConvention())
);

snippet source | anchor

Customize the Action Selection Process

When selecting actions for a given Swagger document, the generator invokes a DocInclusionPredicate against every ApiDescription
that's surfaced by the framework. The default implementation inspects ApiDescription.GroupName and returns true if the value is either null
or equal to the requested document name. However, you can also provide a custom inclusion predicate. For example, if you're using an
attribute-based approach to implement API versioning (e.g. Microsoft.AspNetCore.Mvc.Versioning), you could configure a custom predicate that leverages the versioning attributes instead:

cs
options.DocInclusionPredicate((docName, apiDesc) =>
{
    if (!apiDesc.TryGetMethodInfo(out MethodInfo methodInfo))
    {
        return false;
    }

    var versions = methodInfo.DeclaringType?
        .GetCustomAttributes(true)
        .OfType<ApiVersionAttribute>()
        .SelectMany(attribute => attribute.Versions) ?? [];

    return versions.Any(version => $"v{version}" == docName);
});

snippet source | anchor

Exposing Multiple Documents through the UI

If you're using the SwaggerUI middleware, you'll need to specify any additional OpenAPI endpoints you want to expose.
See List Multiple OpenAPI Documents for more information.

Omit Obsolete Operations and/or Schema Properties

The OpenAPI specification includes a deprecated flag for indicating that an operation is deprecated
(obsolete) and should be refrained from being used. The OpenAPI generator will automatically set this flag if the corresponding action is
decorated with the [Obsolete] attribute. However, instead of setting a flag, you can configure the generator to ignore obsolete actions altogether:

cs
services.AddSwaggerGen(options =>
{
    options.IgnoreObsoleteActions();
});

snippet source | anchor

A similar approach can also be used to omit obsolete properties from Schemas in the OpenAPI document. That is, you can decorate
model properties with [Obsolete] and configure Swashbuckle.AspNetCore to omit those properties when generating JSON schemas:

cs
services.AddSwaggerGen(options =>
{
    options.IgnoreObsoleteProperties();
});

snippet source | anchor

Omit Arbitrary Operations

You can omit operations from the OpenAPI output by decorating individual actions or by applying an application-wide convention.

Decorate Individual Actions

To omit a specific action, decorate it with [ApiExplorerSettings] and set the IgnoreApi property to true:

cs
[HttpDelete("{id}")]
[ApiExplorerSettings(IgnoreApi = true)]
public void Delete(int id)
{
    // ...
}

snippet source | anchor

Omit Actions by Convention

To omit actions by convention instead of decorating them individually, you can apply a custom action convention. For example, you
could wire up the following convention to only document GET operations:

๐Ÿ“ ApiExplorerGetsOnlyConvention.cs

cs
public class ApiExplorerGetsOnlyConvention : IActionModelConvention
{
    public void Apply(ActionModel action)
    {
        action.ApiExplorer.IsVisible = action.Attributes.OfType<HttpGetAttribute>().Any();
    }
}

snippet source | anchor

๐Ÿ“ Startup.cs

cs
services.AddMvc(options =>
    options.Conventions.Add(new ApiExplorerGetsOnlyConvention())
);

snippet source | anchor

Customize Operation Tags (e.g. for UI Grouping)

The OpenAPI specification allows one or more "tags" to be assigned to an operation. The OpenAPI generator
will assign the controller name as the default tag. This is important to note if you're using the SwaggerUI middleware as it uses this
value to group operations.

You can override the default tag by providing a function that applies tags by convention. For example, the following configuration will
tag, and therefore group operations in the UI, by HTTP method:

cs
services.AddSwaggerGen(options =>
{
    options.TagActionsBy(api => [api.HttpMethod]);
});

snippet source | anchor

Change Operation Sort Order (e.g. for UI Sorting)

By default, actions are ordered by assigned tag (see above) before they're grouped into the path-centric, nested structure of the
OpenAPI specification. However, you can change the default ordering of actions with a custom sorting strategy:

cs
services.AddSwaggerGen(options =>
{
    options.OrderActionsBy((apiDesc) => $"{apiDesc.ActionDescriptor.RouteValues["controller"]}_{apiDesc.HttpMethod}");
});

snippet source | anchor

[!NOTE]
This dictates the sort order before actions are grouped and transformed into the OpenAPI format. Therefore it affects the ordering
of groups (i.e. OpenAPI "PathItems"), and the ordering of operations within a group, in the OpenAPI document that is output.

Customize Schema Ids

If the generator encounters complex parameter or response types, it will generate a corresponding JSON schema, add it to the global
components:schemas dictionary, and reference it from the operation description by unique Id. For example, if you have an action
that returns a Product type, then the generated schema will be referenced as follows:

yaml
responses: {
  200: {
    content: {
      "application/json": {
        schema: {
          $ref: "#/components/schemas/Product"
        }
      }
    }
  }
}

However, if it encounters multiple types with the same name but different namespaces (e.g. RequestModels.Product and ResponseModels.Product),
then Swashbuckle.AspNetCore will raise an exception due to "Conflicting schemaIds". In this case, you'll need to provide a custom Id strategy that
further qualifies the name:

cs
services.AddSwaggerGen(options =>
{
    options.CustomSchemaIds((type) => type.FullName);
});

snippet source | anchor

[!NOTE]
See this GitHub issue for support for nested types.

Override Schema for Specific Types

Out-of-the-box, Swashbuckle.AspNetCore performs a best-effort generating JSON schemas that accurately describe your request and response payloads.
However, if you're customizing serialization behavior for certain types in your API, you may need to help it out to get accurate output.

For example, you might have a class with multiple properties that you want to represent in JSON as a comma-separated string. To do this you
would probably implement a custom JsonConverter. In this case, Swashbuckle.AspNetCore doesn't know how the converter is implemented and so you would
need to provide it with a schema that accurately describes the type:

๐Ÿ“ PhoneNumber.cs

cs
public class PhoneNumber
{
    public string CountryCode { get; set; } = string.Empty;

    public string AreaCode { get; set; } = string.Empty;

    public string SubscriberId { get; set; } = string.Empty;
}

snippet source | anchor

๐Ÿ“ Startup.cs

cs
services.AddSwaggerGen(options =>
{
    options.MapType(() => new OpenApiSchema { Type = JsonSchemaType.String });
});

snippet source | anchor

Extend Generator with Operation, Schema and Document Filters

Swashbuckle.AspNetCore exposes a filter pipeline that hooks into the generation process. Once generated, individual metadata objects are passed
into the pipeline where they can be modified further. You can wire up custom filters to enrich the generated Operations, Schemas
and Documents.

Operation Filters

Swashbuckle.AspNetCore retrieves an ApiDescription, part of ASP.NET Core, for every action and uses it to generate a corresponding OpenApiOperation.
Once generated, it passes the OpenApiOperation and the ApiDescription through the list of configured Operation Filters.

In a typical filter implementation, you would inspect the ApiDescription for relevant information (e.g. route information, action attributes etc.)
and then update the OpenApiOperation accordingly. For example, the following filter lists an additional 401 response for all actions that
are decorated with [Authorize]:

๐Ÿ“ AuthResponsesOperationFilter.cs

cs
public class AuthResponsesOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var hasAuthAttributes = context.MethodInfo.DeclaringType?.GetCustomAttributes(true)
            .Union(context.MethodInfo.GetCustomAttributes(true))
            .OfType<AuthorizeAttribute>()
            .Any() ?? false;

        if (hasAuthAttributes)
        {
            operation.Responses ??= [];
            operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
        }
    }
}

snippet source | anchor

๐Ÿ“ Startup.cs

cs
services.AddSwaggerGen(options =>
{
    options.OperationFilter<AuthResponsesOperationFilter>();
});

snippet source | anchor

[!NOTE]
Filter pipelines are DI-aware. That is, you can create filters with constructor parameters and if the parameter types
are registered with the DI framework, they'll be automatically injected when the filters are instantiated.

Schema Filters

Swashbuckle.AspnetCore generates an OpenAPI-flavored JSONSchema for every parameter, response
and property type that's exposed by your endpoints. Once generated, it passes the schema and type through the list of configured
Schema Filters.

The example below adds an AutoRest vendor extension
to inform the AutoRest tool how enums should be modelled when it generates the API client.

๐Ÿ“ AutoRestSchemaFilter.cs

cs
public class AutoRestSchemaFilter : ISchemaFilter
{
    public void Apply(IOpenApiSchema schema, SchemaFilterContext context)
    {
        var type = context.Type;
        if (type.IsEnum && schema is OpenApiSchema concrete)
        {
            concrete.Extensions ??= new Dictionary<string, IOpenApiExtension>();
            concrete.Extensions.Add(
                "x-ms-enum",
                new JsonNodeExtension(
                    new JsonObject
                    {
                        ["name"] = type.Name,
                        ["modelAsString"] = true
                    }
                )
            );
        }
    }
}

snippet source | anchor

๐Ÿ“ Startup.cs

cs
services.AddSwaggerGen(options =>
{
    options.SchemaFilter<AutoRestSchemaFilter>();
});

snippet source | anchor

The example below allows for automatic schema generation of generic Dictionary<Enum, TValue> objects.
Note that this only generates the OpenAPI document; System.Text.Json is not able to parse dictionary enums by default,
so you will need a special JsonConverter, as shown in the .NET documentation.

๐Ÿ“ DictionaryTKeyEnumTValueSchemaFilter.cs

cs
public class DictionaryTKeyEnumTValueSchemaFilter : ISchemaFilter
{
    public void Apply(IOpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema is not OpenApiSchema concrete)
        {
            return;
        }

        // Only run for fields that are a Dictionary<Enum, TValue>
        if (!context.Type.IsGenericType || !context.Type.GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>)))
        {
            return;
        }

        var genericArgs = context.Type.GetGenericArguments();
        var keyType = genericArgs[0];
        var valueType = genericArgs[1];

        if (!keyType.IsEnum)
        {
            return;
        }

        concrete.Type = JsonSchemaType.Object;
        concrete.Properties = keyType.GetEnumNames().ToDictionary(
            name => name,
            name => context.SchemaGenerator.GenerateSchema(valueType, context.SchemaRepository));
    }
}

snippet source | anchor

๐Ÿ“ Startup.cs

cs
services.AddSwaggerGen(options =>
{
    // These will be replaced by DictionaryTKeyEnumTValueSchemaFilter, but are needed to avoid
    // an error. You will need one for every kind of Dictionary<,> you have.
    options.MapType<Dictionary<MyEnum, List<string>>>(() => new OpenApiSchema());
    options.SchemaFilter<DictionaryTKeyEnumTValueSchemaFilter>();
});

snippet source | anchor

Document Filters

Once an OpenApiDocument has been generated, it too can be passed through a set of pre-configured Document Filters.
This gives full control to modify the document however you see fit. To ensure you're still returning valid OpenAPI JSON, you
should have a read through the specification before using this filter type.

The example below provides a description for any tags that are assigned to operations in the document:

cs
public class TagDescriptionsDocumentFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        swaggerDoc.Tags = new HashSet<OpenApiTag>()
        {
            new() { Name = "Products", Description = "Browse/manage the product catalog" },
            new() { Name = "Orders", Description = "Submit orders" }
        };
    }
}

snippet source | anchor

[!NOTE]
If you're using the SwaggerUI middleware, the TagDescriptionsDocumentFilter demonstrated above
could be used to display additional descriptions beside each group of operations.

Add Security Definitions and Requirements

In OpenAPI, you can describe how your API is secured by defining one or more security schemes (e.g. Basic, API key, OAuth2 etc.)
and declaring which of those schemes are applicable globally or for specific operations. For more details, take a look at the
Security Requirement Object in the OpenAPI specification.

In Swashbuckle.AspNetCore, you can define schemes by invoking the AddSecurityDefinition method, providing a name and an instance of
OpenApiSecurityScheme. For example you can define an OAuth 2.0 - implicit flow as follows:

๐Ÿ“ Startup.cs

cs
services.AddSwaggerGen(options =>
{
    // Define the OAuth2.0 scheme that's in use (i.e. Implicit Flow)
    options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows
        {
            Implicit = new OpenApiOAuthFlow
            {
                AuthorizationUrl = new Uri("/auth-server/connect/authorize", UriKind.Relative),
                Scopes = new Dictionary<string, string>
                {
                    ["readAccess"] = "Access read operations",
                    ["writeAccess"] = "Access write operations"
                }
            }
        }
    });
});

snippet source | anchor

[!NOTE]
In addition to defining a scheme, you also need to indicate which operations that scheme is applicable to. You can apply schemes
globally (i.e. to all operations) through the AddSecurityRequirement method. The example below indicates that the scheme called
"oauth2" should be applied to all operations, and that the "readAccess" and "writeAccess" scopes are required. When applying
schemes of type other than "oauth2", the array of scopes must be empty.

๐Ÿ“ Startup.cs

cs
services.AddSwaggerGen(options =>
{
    options.AddSecurityRequirement((document) => new OpenApiSecurityRequirement()
    {
        [new OpenApiSecuritySchemeReference("oauth2", document)] = ["readAccess", "writeAccess"]
    });
});

snippet source | anchor

If you have schemes that are only applicable for certain operations, you can apply them through an Operation filter. For
example, the following filter adds OAuth2 requirements based on the presence of the AuthorizeAttribute:

๐Ÿ“ SecurityRequirementsOperationFilter.cs

cs
public class SecurityRequirementsOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        // Policy names map to scopes
        var requiredScopes = context.MethodInfo
            .GetCustomAttributes(true)
            .OfType<AuthorizeAttribute>()
            .Select(attribute => attribute.Policy!)
            .Distinct()
            .ToList();

        if (requiredScopes.Count > 0)
        {
            operation.Responses ??= [];
            operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
            operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });

            var scheme = new OpenApiSecuritySchemeReference("oauth2", context.Document);

            operation.Security =
            [
                new OpenApiSecurityRequirement
                {
                    [scheme] = requiredScopes
                }
            ];
        }
    }
}

snippet source | anchor

[!NOTE]
If you're using the SwaggerUI middleware, you can enable interactive OAuth2.0 flows that are powered by the emitted
security metadata. See Enabling OAuth2.0 Flows for more details.

Add Security Definitions and Requirements for Bearer authentication

cs
services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("bearer", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.Http,
        Scheme = "bearer",
        BearerFormat = "JWT",
        Description = "JWT Authorization header using the Bearer scheme."
    });
    options.AddSecurityRequirement(document => new OpenApiSecurityRequirement
    {
        [new OpenApiSecuritySchemeReference("bearer", document)] = []
    });
});

snippet source | anchor

Inheritance and Polymorphism

OpenAPI defines the allOf and oneOf keywords for describing
inheritance and polymorphism relationships
in schema definitions. For example, if you're using a base class for models that share common properties you can use the allOf
keyword to describe the inheritance hierarchy. Or, if your serializer supports polymorphic serialization/deserialization, you can use
the oneOf keyword to document all the "possible" schemas for requests/responses that vary by subtype.

Enabling Inheritance

By default, Swashbuckle.AspNetCore flattens inheritance hierarchies. That is, for derived models, the inherited properties are combined and listed
alongside the declared properties. This can cause a lot of duplication in the generated OpenAPI document, particularly when there's multiple subtypes.
It's also problematic if you're using a client generator (e.g. NSwag) and would like to maintain the inheritance hierarchy in the generated
client models. To work around this, you can apply the UseAllOfForInheritance setting, and this will leverage the allOf keyword to
incorporate inherited properties by reference in the generated OpenAPI document:

yaml
Circle: {
  type: "object",
  allOf: [
    {
      $ref: "#/components/schemas/Shape"
    }
  ],
  properties: {
    radius: {
      type: "integer",
      format: "int32",
    }
  },
},
Shape: {
  type: "object",
  properties: {
    name: {
      type: "string",
      nullable: true,
    }
  },
}

Enabling Polymorphism

If your serializer supports polymorphic serialization/deserialization and you would like to list the possible subtypes for an action
that accepts/returns abstract base types, you can apply the UseOneOfForPolymorphism setting. As a result, the generated request/response
schemas will reference a collection of "possible" schemas instead of just the base class schema:

json
"requestBody": {
  "content": {
    "application/json": {
      "schema": {
        "oneOf": [
          {
            "$ref": "#/components/schemas/Rectangle"
          },
          {
            "$ref": "#/components/schemas/Circle"
          }
        ]
      }
    }
  }
}

Detecting Subtypes

As inheritance and polymorphism relationships can often become quite complex, not just in your own models but also within the .NET class
library, Swashbuckle.AspNetCore is selective about which hierarchies it does and doesn't expose in the generated OpenAPI document. By default, it will
pick up any subtypes that are defined in the same assembly as a given base type. If you'd like to override this behavior, you can provide a
custom selector method:

cs
services.AddSwaggerGen(options =>
{
    options.UseAllOfForInheritance();

    options.SelectSubTypesUsing(baseType =>
    {
        return typeof(Program).Assembly.GetTypes().Where(type => type.IsSubclassOf(baseType));
    });
});

snippet source | anchor

[!NOTE]
If you're using the Swashbuckle Annotations library, it
contains a custom selector that's based on the presence of [JsonDerivedType] attributes on base class definitions. This
way, you can use simple attributes to explicitly list the inheritance and/or polymorphism relationships you want to expose.
To enable this behavior, check out the Annotations docs.

Describing Discriminators

In conjunction with the oneOf and/or allOf keywords, OpenAPI supports a discriminator field on base schema definitions.
This keyword points to the property that identifies the specific type being represented by a given payload. In addition to the property
name, the discriminator description may also include a mapping which maps discriminator values to specific schema definitions.

For example, the Newtonsoft serializer supports polymorphic serialization/deserialization by emitting/accepting a "$type" property on
JSON instances. The value of this property will be the assembly qualified type name
of the type represented by a given JSON instance. So, to explicitly describe this behavior in OpenAPI, the corresponding request/response
schema could be defined as follows:

yaml
components: {
  schemas: {
    Shape: {
      required: [
        "$type"
      ],
      type: "object",
      properties: {
        $type: {
          type: "string"
        },
        discriminator: {
          propertyName: "$type",
          mapping: {
            Rectangle: "#/components/schemas/Rectangle",
            Circle: "#/components/schemas/Circle"
          }
        }
      }
    },
    Rectangle: {
      type: "object",
      allOf: [
        {
          "$ref": "#/components/schemas/Shape"
        }
      ],
      ...
    },
    Circle: {
      type: "object",
      allOf: [
        {
          "$ref": "#/components/schemas/Shape"
        }
      ],
      ...
    }
  }
}

If UseAllOfForInheritance or UseOneOfForPolymorphism is enabled, and your serializer supports (and has enabled) emitting/accepting
a discriminator property, then Swashbuckle will automatically generate the corresponding discriminator metadata on base schema definitions.

Alternatively, if you've customized your serializer to support polymorphic serialization/deserialization, you can provide some custom
selector functions to determine the discriminator name and corresponding mapping:

cs
services.AddSwaggerGen(options =>
{
    options.UseAllOfForInheritance();

    options.SelectDiscriminatorNameUsing((baseType) => "TypeName");
    options.SelectDiscriminatorValueUsing((subType) => subType.Name);
});

snippet source | anchor

[!NOTE]
If you're using the Swashbuckle Annotations library, it
contains custom selector functions that are based on the presence of [JsonPolymorphic] and [JsonDerivedType] attributes on base
class definitions. This way, you can use simple attributes to explicitly provide discriminator metadata. To enable this behavior, check
out the Annotations documentation.


File: docs/configure-and-customize-swaggerui.md

Configuration and Customization of `Swashbuckle.AspNetCore.SwaggerUI`

Change Relative Path to the UI

By default, the Swagger UI will be exposed at /swagger. If necessary, you can alter this when enabling the SwaggerUI middleware:

cs
app.UseSwaggerUI(options =>
{
    options.RoutePrefix = "api-docs";
});

snippet source | anchor

Change Document Title

By default, the Swagger UI will have a generic document title. When you have multiple OpenAPI documents open, it can be difficult to
tell them apart. You can alter this when enabling the SwaggerUI middleware:

cs
app.UseSwaggerUI(options =>
{
    options.DocumentTitle = "My Swagger UI";
});

snippet source | anchor

Change CSS or JS Paths

By default, the Swagger UI includes default CSS and JavaScript, but if you wish to change the path or URL (for example to use a CDN)
you can override the defaults as shown below:

cs
app.UseSwaggerUI(options =>
{
    options.StylesPath = "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.29.1/swagger-ui.min.css";
    options.ScriptBundlePath = "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.29.1/swagger-ui-bundle.min.js";
    options.ScriptPresetsPath = "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.29.1/swagger-ui-standalone-preset.min.js";
});

snippet source | anchor

List Multiple OpenAPI Documents

When enabling the middleware, you're required to specify one or more OpenAPI endpoints (fully qualified or relative to the UI page) to
power the UI. If you provide multiple endpoints, they'll be listed in the top right corner of the page, allowing users to toggle between
the different documents. For example, the following configuration could be used to document different versions of an API.

cs
app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
    options.SwaggerEndpoint("/swagger/v2/swagger.json", "V2 Docs");
});

snippet source | anchor

Apply swagger-ui Parameters

swagger-ui ships with its own set of configuration parameters, all described
by the swagger-ui Configuration.
In Swashbuckle.AspNetCore, most of these are surfaced through the SwaggerUI middleware options:

cs
app.UseSwaggerUI(options =>
{
    options.DefaultModelExpandDepth(2);
    options.DefaultModelRendering(ModelRendering.Model);
    options.DefaultModelsExpandDepth(-1);
    options.DisplayOperationId();
    options.DisplayRequestDuration();
    options.DocExpansion(DocExpansion.None);
    options.EnableDeepLinking();
    options.EnableFilter();
    options.EnablePersistAuthorization();
    options.EnableTryItOutByDefault();
    options.MaxDisplayedTags(5);
    options.ShowExtensions();
    options.ShowCommonExtensions();
    options.EnableValidator();
    options.SupportedSubmitMethods(SubmitMethod.Get, SubmitMethod.Head);
    options.UseRequestInterceptor("(request) => { return request; }");
    options.UseResponseInterceptor("(response) => { return response; }");
});

snippet source | anchor

Inject Custom JavaScript

To tweak the behavior, you can inject additional JavaScript files by adding them to your wwwroot folder and specifying
the relative paths in the middleware options:

cs
app.UseSwaggerUI(options =>
{
    options.InjectJavascript("/swagger-ui/custom.js");
});

snippet source | anchor

Inject Custom CSS

To tweak the look and feel, you can inject additional CSS stylesheets by adding them to your wwwroot folder and specifying the
relative paths in the middleware options:

cs
app.UseSwaggerUI(options =>
{
    options.InjectStylesheet("/swagger-ui/custom.css");
});

snippet source | anchor

Customize index.html

To customize the UI beyond the basic options listed above, you can provide your own version of the swagger-ui index.html page:

cs
app.UseSwaggerUI(options =>
{
    options.IndexStream = () => typeof(Program).Assembly
        .GetManifestResourceStream("CustomUIIndex.Swagger.index.html"); // Requires file to be added as an embedded resource
});

snippet source | anchor

xml

[!TIP]
To get started, you should base your custom index.html on the built-in version.

Enable OAuth2.0 Flows

swagger-ui has built-in support to participate in OAuth2.0 authorization flows. It interacts with authorization and/or token
endpoints, as specified in the OpenAPI JSON, to obtain access tokens for subsequent API calls. See
Adding Security Definitions and Requirements for
an example of adding OAuth2.0 metadata to the generated Swagger.

If your OpenAPI endpoint includes the appropriate security metadata, the UI interaction should be automatically enabled. However, you
can further customize OAuth support in the UI with the following settings below. See the
Swagger-UI documentation for more information.

cs
app.UseSwaggerUI(options =>
{
    options.OAuthClientId("test-id");
    options.OAuthClientSecret("test-secret");
    options.OAuthUsername("test-user");
    options.OAuthRealm("test-realm");
    options.OAuthAppName("test-app");
    options.OAuth2RedirectUrl("url");
    options.OAuthScopeSeparator(" ");
    options.OAuthScopes("scope1", "scope2");
    options.OAuthAdditionalQueryStringParams(new Dictionary<string, string> { ["foo"] = "bar" });
    options.OAuthUseBasicAuthenticationWithAccessCodeGrant();
    options.OAuthUsePkce();
});

snippet source | anchor

Use client-side request and response interceptors

To use custom interceptors on requests and responses going through swagger-ui you can define them as JavaScript functions
in the configuration:

cs
app.UseSwaggerUI(options =>
{
    options.UseRequestInterceptor("(req) => { req.headers['x-my-custom-header'] = 'MyCustomValue'; return req; }");
    options.UseResponseInterceptor("(res) => { console.log('Custom interceptor intercepted response from:', res.url); return res; }");
});

snippet source | anchor

This can be useful in a range of scenarios where you might want to append local XSRF tokens to all requests, for example:

cs
app.UseSwaggerUI(options =>
{
    options.UseRequestInterceptor("(req) => { req.headers['X-XSRF-Token'] = localStorage.getItem('xsrf-token'); return req; }");
});

snippet source | anchor

Use `MapSwaggerUI` with endpoint routing

MapSwaggerUI is an endpoint-routing alternative to UseSwaggerUI. The options API is the same, so all customization examples on this page also apply when using MapSwaggerUI.

cs
app.MapSwagger();
app.MapSwaggerUI("swagger", options => options.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs"));

snippet source | anchor

The main differences are:

  • UseSwaggerUI adds middleware directly to the request pipeline and returns IApplicationBuilder.

  • MapSwaggerUI maps the Swagger UI via endpoint routing and returns IEndpointConventionBuilder.

  • Because MapSwaggerUI returns an endpoint convention builder, you can attach endpoint metadata/conventions (for example, authorization policies) directly to the mapped UI endpoint.

cs
app.MapSwaggerUI("swagger-auth")
   .RequireAuthorization(); // Remember to also add RequireAuthorization to MapSwagger.

snippet source | anchor


File: docs/migrating-to-v10.md

Migrating to Swashbuckle.AspNetCore v10

[!IMPORTANT]
This document describes the breaking changes introduced in Swashbuckle.AspNetCore v10, and how to migrate from v9.x to v10+.

Why breaking changes?

While the OpenAPI 3.1 specification is a minor release compared to OpenAPI 3.0, the OpenAPI specification does
not use Semantic Versioning (SemVer). The changes introduced between the two versions are quite breaking in a practical sense,
so major changes were required to be made to Microsoft.OpenApi, the package which Swashbuckle.AspNetCore
builds upon, in order to allow applications to produce OpenAPI 3.1 documents.

These changes were introduced in Microsoft.OpenApi v2.0.0, which does follow SemVer. As a result,
Swashbuckle.AspNetCore v10+ now depends on Microsoft.OpenApi v2+ to allow users to produce OpenAPI 3.1 documents, fulfilling a
long-standing feature request: Plans on official support for OpenApi 3.1.0 #2349.

These changes are unfortunately required, even if you still wish to target Swagger 2.0 or OpenAPI 3.0 documents, as the same library is used
to produce all three document format versions.

For the same reason, ASP.NET Core v10+ also depends on Microsoft.OpenApi v2+ if you use the Microsoft.AspNetCore.OpenApi
NuGet package, so these changes were also required to allow applications using ASP.NET Core 10 to use Swashbuckle.AspNetCore effectively with
minimal friction. This also helps support users who may wish to migrate an application from Swashbuckle.AspNetCore to Microsoft.AspNetCore.OpenApi
(for example if they need native AoT support). More information about the breaking changes in ASP.NET Core 10 can be found in this
document: What's new in ASP.NET Core in .NET 10.

The refactoring required to support OpenAPI 3.1 in Swashbuckle.AspNetCore was significant. If you're interested in what exactly what was changed,
you can check out the PR to implement it that was worked on over the course of .NET 10's development (it's quite large): Support .NET 10 #3283.

How do I enable OpenAPI 3.1 support?

By default, to minimise breaking behavioural changes, Swashbuckle.AspNetCore v10+ will continue to produce OpenAPI 3.0 documents by default.

To upgrade your OpenAPI documents to output using version 3.1 of the OpenAPI specification, you can override the version as shown in the code snippet below.

cs
app.UseSwagger(options =>
{
    options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_1;
});

snippet source | anchor

How do I migrate to Swashbuckle.AspNetCore v10+?

[!TIP]
It is strongly recommended that you upgrade to Swashbuckle.AspNetCore v9.0.6 before upgrading to v10.

The majority of the breaking changes you may encounter when migrating to Swashbuckle.AspNetCore v10+ are due to the underlying
changes in Microsoft.OpenApi v2.0.0+. The v2 migration guide for Microsoft.OpenApi provides a
detailed overview of the breaking changes and how to migrate your code from Microsoft.OpenApi v1.x to v2.x. The Microsoft.OpenApi
breaking changes document should be your primary reference when migrating to Swashbuckle.AspNetCore v10+.

The chances of encountering breaking changes when migrating to Swashbuckle.AspNetCore v10+ depend on how extensively you use the
Swashbuckle.AspNetCore extensibility points, such as custom filters, to generate the OpenAPI document. If you do not use any custom logic
and do not depend on any other third-party libraries that depend on Microsoft.OpenApi v1.x, you may not encounter any breaking changes at all.

In cases where Swashbuckle.AspNetCore has a breaking change, this is because the types from the underlying Microsoft.OpenApi library
are exposed in the public API of Swashbuckle.AspNetCore, so the breaking change bubbles up through the public API surface to cause compilation
issues in your code. For example the signature for IRequestBodyAsyncFilter.ApplyAsync() has changed as shown below:

diff
- Swashbuckle.AspNetCore.SwaggerGen.IRequestBodyAsyncFilter.ApplyAsync(Microsoft.OpenApi.Models.OpenApiRequestBody requestBody, Swashbuckle.AspNetCore.SwaggerGen.RequestBodyFilterContext context, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task
+ Swashbuckle.AspNetCore.SwaggerGen.IRequestBodyAsyncFilter.ApplyAsync(Microsoft.OpenApi.IOpenApiRequestBody requestBody, Swashbuckle.AspNetCore.SwaggerGen.RequestBodyFilterContext context, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task

Migration Overview

Migrating to Swashbuckle.AspNetCore v10+ will likely involve changes in the following areas:

  • Update any NuGet package references for Swashbuckle.AspNetCore and Microsoft.OpenApi to v10.0.0+ and v2.3.0+ respectively.

  • Update any using directives that reference types from the Microsoft.OpenApi.Models namespace to use the new namespace Microsoft.OpenApi.

  • Update model references (e.g. OpenApiSchema) to use the new interfaces (e.g. IOpenApiSchema) and use the relevant concrete types to mutate them (e.g. OpenApiSchema). An example of this is shown below for an ISchemaFilter implementation:

    csharp
    public void Apply(IOpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema is OpenApiSchema openApiSchema)
        {
             // The properties are only mutable on the concrete type
             openApiSchema.Type = JsonSchemaType.String;
        }
    }
  • Update any use of .Reference properties (e.g. OpenApiSchema.ReferenceV3) to use the new *Reference class instead (e.g. OpenApiSchemaReference).

  • Replace usage of the OpenApiSchema.Type property using a string (e.g. "string" or "boolean") with the JsonSchemaType flags enumeration.

  • Replace usage of the OpenApiSchema.Nullable property by OR-ing the JsonSchemaType.Null value to OpenApiSchema.Type (e.g. schema.Type |= JsonSchemaType.Null;).

  • Remove any use of the now-deprecated WithOpenApi() extension method in Microsoft.AspNetCore.OpenApi.

  • Updating any use of AddSecurityRequirement() to use a Func<OpenApiDocument, OpenApiSecurityRequirement> (documentation).

  • Updating some collections to use specific concrete types instead of interfaces if collection expressions were used, for example using HashSet<OpenApiTag> with OpenApiDocument.Tags which is now an ISet<OpenApiTag>.