asp.net core webapi 如何使用swagger,下面直入主題給出乾貨。
1、NuGet 安裝Swashbuckle.AspNetCore
2、Startup檔案的ConfigureServices註冊swagger服務,重點是如何在頭部新增Bearer Token。
//註冊Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo() { Title = "Demo WebAPI", Version = "v1.0.0.1" });
//新增 Bearer Token 認證
c.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Description = "請輸入帶有Bearer的Token",
Name = "Authorization",
In = Microsoft.OpenApi.Models.ParameterLocation.Header,
Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference() { Id = "Bearer", Type = ReferenceType.SecurityScheme } }, Array.Empty<string>() } });
//顯示註釋
var xmlDocPath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Demo.WebAPI.xml");
if (System.IO.File.Exists(xmlDocPath))
{
c.IncludeXmlComments(xmlDocPath);
}
});
3、Startup檔案Configure配置swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Demo API V1");
});
4、新增一個UserController測試效果
/// <summary>
/// 測試
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("Test")]
public string Test()
{
return Guid.NewGuid().ToString();
}
5、看看效果圖,你學會了嗎