ASP.NET Core Swagger 相关使用

添加Swagger

Nuget安装Swashbuckle.AspNetCore包,添加Swagger

//创建Swagger
builder.Services.AddSwaggerGen(options =>
{
  options.SwaggerDoc("v1", new OpenApiInfo { Title = "API标题", Version = "v1", Description = $"NetCore Http API v1", });
});

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");//网页UI
    //c.RoutePrefix = string.Empty;//路由,默认路由:/swagger/index.html
    c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);//设置为None可折叠所有方法
    c.DefaultModelsExpandDepth(-1); //-1 可不显示Models
});

隐藏API

Swagger中不显示某一个API,在方法/类添加以下属性。但是实际上Api还是可以调用

[ApiExplorerSettings(IgnoreApi = true)]

显示注释

项目csproj文件添加以下配置

<PropertyGroup>
  <GenerateDocumentationFile>True</GenerateDocumentationFile>
</PropertyGroup> 

Swagger添加配置

builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "API标题", Description = "API描述" });
    //第二个参数为是否显示控制器注释,我们选择true
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"), true);
});

在控制台方法中添加/// <summary>注释,Swagger就会显示注释。

添加JWT配置

builder.Services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
    {
        Description = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    options.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] { "readAccess", "writeAccess" }
        }
    });
});

多个版本

builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("default", new OpenApiInfo { Title = "API标题", Version = "default", Description = $"NetCore Http API default", });
    options.SwaggerDoc("v1", new OpenApiInfo { Title = "API标题", Version = "v1", Description = $"NetCore Http API v1", });
    options.SwaggerDoc("v2", new OpenApiInfo { Title = "API标题", Version = "v2", Description = $"NetCore Http API v2", });
    options.SwaggerDoc("v3", new OpenApiInfo { Title = "API标题", Version = "v3", Description = $"NetCore Http API v3" });

    //第二个参数为是否显示控制器注释,我们选择true
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"), true);
    options.DocInclusionPredicate((docName, description) =>
         docName switch
        {
            "default" => !description.RelativePath!.StartsWith("api/v"),
            "v1" => description.RelativePath!.StartsWith("api/v1"),
            "v2" => description.RelativePath!.StartsWith("api/v2"),
            "v3" => description.RelativePath!.StartsWith("api/v3"),
            _ => true
        });
});

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/default/swagger.json", "API default");
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");
    c.SwaggerEndpoint("/swagger/v2/swagger.json", "API V2");
    c.SwaggerEndpoint("/swagger/v3/swagger.json", "API V3");
    //c.RoutePrefix = string.Empty;//路由,默认路由:/swagger/index.html
    c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);//设置为None可折叠所有方法
    c.DefaultModelsExpandDepth(-1); //-1 可不显示Models
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章