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
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章