Swagger

在 .NET 專案導入 Swagger 需要三個步驟:安裝套件、讓 csproj 產生 XML 說明檔,最後在 Program.cs 註冊。

下載套件:Swashbuckle.AspNetCore

(1) 網站 .csproj 設定

在 <PropertyGroup> 標籤結尾新增:

  • <OutputPath> 標籤,值放 bin
  • <GenerateDocumentationFile> 標籤,值放 true
  • <DocumentationFile> 標籤,值放 $(OutputPath)$(AssemblyName).xml

可將 XML 說明轉成實體檔案,供 Swagger 套件讀取。

(2) Program.cs 加入以下設定

//Swagger 產生器是負責取得 API 的規格並產生 SwaggerDocument 物件。
builder.Services.AddSwaggerGen();

//Swagger Middleware 負責路由,提供 SwaggerDocument 物件。
app.UseSwagger();

//將 SwaggerDocument 物件變成漂亮的介面。
app.UseSwaggerUI(swaggerService =>
{
    swaggerService.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

參考資料