1 Swagger是什么?
Swagger用於描述 REST API。 它允許計算機和人員了解服務的功能,而無需直接訪問實現(源代碼、網絡訪問、文檔)。
2 安裝
Swashbuckle.AspNetCore
添加Swagger生成器
將Swagger生成器添加到 Startup.ConfigureServices 方法中的服務集合中:
services.AddSwaggerGen();
配置Swagger中間件
在 Startup.Configure 方法中,啟用中間件為生成的 JSON 文檔和 Swagger UI 提供服務:
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
XML注釋
- 在“解決方案資源管理器”中右鍵單擊該項目,然后選擇“編輯< project_name>.csproj” 。
- 手動將PropertyGroup添加:
<GenerateDocumentationFile>true</GenerateDocumentationFile>
更改services.AddSwaggerGen();代碼如下:
services.AddSwaggerGen((c =>
{
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
}));