Customize Swagger with ASP.NET Core API

Install NuGet package Swashbuckle.AspNetCore

Register SwaggerGen in Startup.ConfigureService

Add Authorization

using Microsoft.OpenApi.Models;

...

services.AddSwaggerGen(c =>
{
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Name = "Authorization",
        BearerFormat = "JWT",
        Scheme = "Bearer",
        Description = "Specify the authorization token.",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.Http
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                    }
                },
            new string[] {}
        }
    });
});

 

Use Swagger and SwaggerUI in Startup.Configure

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.EnableTryItOutByDefault();
    c.EnablePersistAuthorization();    // store authorize token
    c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
});

 

创建时间:6/26/2022 12:17:21 AM 修改时间:11/29/2022 2:04:33 PM