Swagger介紹(https://swagger.io/)
Simplify API development for users, teams, and enterprises with the Swagger open source and professional toolset.
安裝Swagger Package
通過Nuget來安裝,輸入“Swashbuckle.AspNetCore”,將需要安裝的工程打勾,點擊Install即可。
配置Swagger
打開Startup.cs類,在ConfigureServices方法中配置Swagger服務
#region Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "My API",
Description = "My Web API HUB",
TermsOfService = new Uri("http://www.baidu.com"),
Contact = new OpenApiContact
{
Name = "Jonny Yan",
Email = "[email protected]",
Url = new Uri("http://www.baidu.com"),
},
License = new OpenApiLicense
{
Name = "Use under LICX",
Url = new Uri("http://www.baidu.com"),
}
});
});
#endregion
編輯Config方法
#region Swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Web API HUB");
c.RoutePrefix = "";//路徑配置,設置爲空,表示直接在根域名(localhost:5000)訪問該文件
});
#endregion
設置Swagger爲默認頁
打開launchSettings.json文件,將launchUrl註銷即可
驗證Swagger
按F5啓動項目,如果頁面顯示Swagger home page則配置成功
顯示Action註釋
- 將註釋信息輸出到xml文件
- 編輯Startup.cs文件,在註冊Swagger服務中讀取xml文件
//讀取Action註釋
var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "Default.xml");
c.IncludeXmlComments(xmlPath, true);
- 按F5查看結果
- 集成Authorization(後續章節回記錄如何實現JWT認證)
打開Startup.cs文件,修改fanConfigureServices方法,在註冊Swagger的地方增加安全認證定義
#region Token綁定到ConfigureServices
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT授權(數據將在請求頭中進行傳輸) 直接在下框中輸入Bearer {token}",
Name = "Authorization",//jwt默認的參數名稱
In = ParameterLocation.Header,//jwt默認存放Authorization信息的位置(請求頭中)
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference{
Id = "Bearer", //The name of the previously defined security scheme.
Type = ReferenceType.SecurityScheme
}
},new List<string>()}
});
#endregion
- 查看效果