開始使用 Swashbuckle 及 ASP.NET Core

注意

.NET 8 和更新版本中不支援使用 Swashbuckle 的建置時間 OpenAPI 文件產生。 如需支援的建置時間替代方案,請參閱 使用 Swagger / OpenAPI ASP.NET Core Web API 檔。 .NET 8 仍然支援產生運行時間檔。

Swashbuckle 有三個主要元件:

  • Swashbuckle.AspNetCore.Swagger:Swagger 物件模型和中介軟體,用來公開 SwaggerDocument 物件作為 JSON 端點。

  • Swashbuckle.AspNetCore.SwaggerGen:Swagger 產生器,可直接從您的路由、控制器和模型建置 SwaggerDocument 物件。 它通常會結合 Swagger 端點中介軟體,以便自動公開 Swagger JSON。

  • Swashbuckle.AspNetCore.SwaggerUI:Swagger UI 工具的內嵌版本。 它可解譯 Swagger JSON 來建置描述 Web API 功能的可自訂豐富體驗。 其中包括公用方法的內建測試載入器。

套件安裝

可使用下列方法新增 Swashbuckle:

  • 從 [套件管理員主控台] 視窗中:

    • 移至 [檢視]>[其他視窗]>[套件管理員主控台]

    • 瀏覽至 .csproj 檔案所在的目錄

    • 執行以下 命令:

      Install-Package Swashbuckle.AspNetCore -Version 6.5.0
      
  • 從 [管理 NuGet 套件] 對話方塊中:

    • 在 [方案總管]>[管理 NuGet 套件] 中,以滑鼠右鍵按一下專案
    • 將 [套件來源] 設定為 "nuget.org"
    • 請確定已啟用 [包含發行前版本] 選項
    • 在搜尋方塊中輸入 "Swashbuckle.AspNetCore"
    • 從 [瀏覽] 索引標籤中選取最新的 "Swashbuckle.AspNetCore" 套件,並按一下 [安裝]

新增和設定 Swagger 中介軟體

將 Swagger 產生器新增至 Program.cs 中的服務集合:

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

只有最小 API 需要上述範例中的 AddEndpointsApiExplorer 呼叫。 如需詳細資訊,請參閱這篇 StackOverflow 文章

啟用中介軟體以處理產生的 JSON 文件和 Swagger UI,還有在 Program.cs 中:

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

上述程式碼只有在目前的環境設定為 [開發] 時,才會新增 Swagger 中介軟體。 方法 UseSwaggerUI 呼叫會啟用 Swagger UI 工具的內嵌版本。

啟動應用程式,並瀏覽至 https://localhost:<port>/swagger/v1/swagger.json。 描述端點的產生文件隨即出現,如 OpenAPI 規格 (openapi.json) 中所示。

您可以在 https://localhost:<port>/swagger 找到 Swagger UI。 透過 Swagger UI 探索 API,並將其併入其他程式。

提示

若要在應用程式的根目錄 (https://localhost:<port>/) 上提供 Swagger UI,請將 RoutePrefix 屬性設為空字串:

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
    options.RoutePrefix = string.Empty;
});

若使用目錄搭配 IIS 或 反向 Proxy,請將 Swagger 端點設定為使用 ./ 前置詞的相對路徑。 例如: ./swagger/v1/swagger.json 。 使用 /swagger/v1/swagger.json 指示應用程式在 URL 的真實根目錄 (若已使用,請加上路由前置詞) 尋找 JSON 檔案。 例如,使用 https://localhost:<port>/<route_prefix>/swagger/v1/swagger.json 而不是 https://localhost:<port>/<virtual_directory>/<route_prefix>/swagger/v1/swagger.json

注意

根據預設,在 3.0 版的規格中 (正式名稱為 OpenAPI 規格),Swashbuckle 會產生並公開 Swagger JSON。 若要支援回溯相容性,您可以選擇改為以 2.0 格式公開 JSON。 對於目前支援 OpenAPI 2.0 版的 Microsoft Power Apps 和 Microsoft Flow 之類的整合來說,這個 2.0 格式很重要。 若要選擇使用 2.0 格式,請在 Program.cs 中設定 SerializeAsV2屬性:

app.UseSwagger(options =>
{
    options.SerializeAsV2 = true;
});

自訂和擴充

Swagger 提供用來記載物件模型和自訂 UI 以符合佈景主題的選項。

API 資訊與描述

傳遞至 AddSwaggerGen 方法的設定動作會新增作者、授權和描述等資訊。

Program.cs 中,匯入下列命名空間以使用 OpenApiInfo 類別:

using Microsoft.OpenApi.Models;

使用 OpenApiInfo 類別,修改顯示在 UI 中的資訊:

builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "ToDo API",
        Description = "An ASP.NET Core Web API for managing ToDo items",
        TermsOfService = new Uri("https://example.com/terms"),
        Contact = new OpenApiContact
        {
            Name = "Example Contact",
            Url = new Uri("https://example.com/contact")
        },
        License = new OpenApiLicense
        {
            Name = "Example License",
            Url = new Uri("https://example.com/license")
        }
    });
});

Swagger UI 會顯示版本資訊:

Swagger UI with version information: description, author, and license.

XML 註解

XML 註解可以使用下列方式啟用:

  • 在 [方案總管] 中用滑鼠右鍵按一下專案,然後選取 Edit <project_name>.csproj
  • GenerateDocumentationFile 新增至 .csproj 檔案:
<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

啟用 XML 註解,可提供未記載之公用類型與成員的偵錯資訊。 未記載的類型和成員會以警告訊息表示。 例如,下列訊息指出警告碼 1591 的違規:

warning CS1591: Missing XML comment for publicly visible type or member 'TodoController'

在專案檔中定義要忽略的警告碼清單 (以分號分隔),即可隱藏警告。 將警告碼附加至 $(NoWarn); 也會套用 C# 預設值

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

若只要針對特定成員隱藏,請將程式碼放在 #pragma 警告前置處理器指示詞中。 針對不應該透過 API 文件公開的程式碼,此方法非常有用。在下列範例中,會針對整個 TodoContext 類別忽略警告碼 CS1591。 會在類別定義結尾處還原強制執行的警告碼。 以逗號分隔清單指定多個警告碼。

namespace SwashbuckleSample.Models;

#pragma warning disable CS1591
public class TodoContext : DbContext
{
    public TodoContext(DbContextOptions<TodoContext> options) : base(options) { }

    public DbSet<TodoItem> TodoItems => Set<TodoItem>();
}
#pragma warning restore CS1591

設定 Swagger 以使用先前指示所產生的 XML 檔案。 對於 Linux 或非 Windows 作業系統,檔案名稱和路徑可以區分大小寫。 例如,TodoApi.XML 檔案在 Windows 上有效,但在 CentOS 上則無效。

builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "ToDo API",
        Description = "An ASP.NET Core Web API for managing ToDo items",
        TermsOfService = new Uri("https://example.com/terms"),
        Contact = new OpenApiContact
        {
            Name = "Example Contact",
            Url = new Uri("https://example.com/contact")
        },
        License = new OpenApiLicense
        {
            Name = "Example License",
            Url = new Uri("https://example.com/license")
        }
    });

    // using System.Reflection;
    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});

在上述程式碼中,Reflection 用來建置與 Web API 專案名稱相符的 XML 檔案名稱。 AppContext.BaseDirectory 屬性用來建構 XML 檔案的路徑。 某些 Swagger 功能 (例如輸入參數的結構描述,或來自相對應屬性的 HTTP 方法和回應碼) 能在不使用 XML 文件檔案的情況下運作。 對於大部分的功能 (也就是方法摘要,以及參數和回應碼的描述) 而言,皆必須使用 XML 檔案。

透過在區段標題新增描述,對動作新增三斜線註解,可增強 Swagger UI。 在 Delete 動作上方新增 <summary> 元素:

/// <summary>
/// Deletes a specific TodoItem.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(long id)
{
    var item = await _context.TodoItems.FindAsync(id);

    if (item is null)
    {
        return NotFound();
    }

    _context.TodoItems.Remove(item);
    await _context.SaveChangesAsync();

    return NoContent();
}

Swagger UI 會顯示上述程式碼的 <summary> 項目的內部文字:

Swagger UI showing XML comment 'Deletes a specific TodoItem.' for the DELETE method.

UI 是由產生的 JSON 結構描述所驅動:

"delete": {
    "tags": [
        "Todo"
    ],
    "summary": "Deletes a specific TodoItem.",
    "parameters": [
        {
            "name": "id",
            "in": "path",
            "description": "",
            "required": true,
            "schema": {
                "type": "integer",
                "format": "int64"
            }
        }
    ],
    "responses": {
        "200": {
            "description": "Success"
        }
    }
},

請將 <remarks>Create 元素新增至 動作方法文件。 它會補充 <summary> 項目中指定的資訊,並提供更強固的 Swagger UI。 <remarks> 元素內容可以包含文字、JSON 或 XML。

/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <param name="item"></param>
/// <returns>A newly created TodoItem</returns>
/// <remarks>
/// Sample request:
///
///     POST /Todo
///     {
///        "id": 1,
///        "name": "Item #1",
///        "isComplete": true
///     }
///
/// </remarks>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    await _context.SaveChangesAsync();

    return CreatedAtAction(nameof(Get), new { id = item.Id }, item);
}

請注意使用這些額外註解的 UI 增強功能:

Swagger UI with additional comments shown.

資料註解

使用 System.ComponentModel.DataAnnotations 命名空間中找到的屬性來標記模型,以協助驅動 Swagger UI 元件。

[Required] 屬性 (attribute) 新增至 TodoItem 類別的 Name 屬性 (property):

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace SwashbuckleSample.Models;

public class TodoItem
{
    public long Id { get; set; }

    [Required]
    public string Name { get; set; } = null!;

    [DefaultValue(false)]
    public bool IsComplete { get; set; }
}

這個屬性的存在會變更 UI 行為,並改變基礎的 JSON 結構描述:

"schemas": {
    "TodoItem": {
        "required": [
            "name"
        ],
        "type": "object",
        "properties": {
            "id": {
                "type": "integer",
                "format": "int64"
            },
            "name": {
                "type": "string"
            },
            "isComplete": {
                "type": "boolean",
                "default": false
            }
        },
        "additionalProperties": false
    }
},

[Produces("application/json")] 屬性新增至 API 控制器。 其目的是要宣告控制器的動作支援回應內容類型為 application/json

[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
public class TodoController : ControllerBase
{

[媒體型別] 下拉式清單會選取此內容類型,作為控制器 GET 動作的預設值:

Swagger UI with default response content type

當 Web API 中的資料註釋使用量增加時,UI 和 API 說明頁面會變得更清楚且更有用。

描述回應類型

取用 Web API 的開發人員最關心的是傳回的內容:特別是回應類型和錯誤碼 (如果不是標準的話)。 回應類型和錯誤碼會在 XML 註解及資料註解中表示。

Create 動作在成功時會傳回 HTTP 201 狀態碼。 張貼的要求主體為 Null 時,會傳回 HTTP 400 狀態碼。 如果 Swagger UI 中沒有適當的文件,取用者便會缺乏對這些預期結果的了解。 在下列範例中新增強調顯示的那幾行來修正該問題:

/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <param name="item"></param>
/// <returns>A newly created TodoItem</returns>
/// <remarks>
/// Sample request:
///
///     POST /Todo
///     {
///        "id": 1,
///        "name": "Item #1",
///        "isComplete": true
///     }
///
/// </remarks>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    await _context.SaveChangesAsync();

    return CreatedAtAction(nameof(Get), new { id = item.Id }, item);
}

現在,Swagger UI 清楚記載了預期的 HTTP 回應碼:

Swagger UI showing POST Response Class description 'Returns the newly created Todo item' and '400 - If the item is null' for status code and reason under Response Messages.

可以使用慣例作為替代方案,明確裝飾 [ProducesResponseType] 的個別動作。 如需詳細資訊,請參閱使用 Web API 慣例

為了支援 [ProducesResponseType] 裝飾,Swashbuckle.AspNetCore.Annotations 套件提供的擴充功能,可啟用和擴充回應、結構描述和參數中繼資料。

自訂 UI

預設 UI 既可運作又能呈現。 不過,API 的文件頁面應該表示您的品牌或佈景主題。 設定 Swashbuckle 元件商標時,需要新增資源來處理靜態檔案,然後建置裝載這些檔案的資料夾結構。

啟用靜態檔案中介軟體:

app.UseHttpsRedirection();
app.UseStaticFiles();
app.MapControllers();

若要插入其他 CSS 樣式表,請將它們新增至專案的 wwwroot 資料夾,並在中介軟體選項中指定相對路徑:

app.UseSwaggerUI(options =>
{
    options.InjectStylesheet("/swagger-ui/custom.css");
});

其他資源

檢視或下載範例程式碼 \(英文\) (如何下載)

Swashbuckle 有三個主要元件:

  • Swashbuckle.AspNetCore.Swagger:Swagger 物件模型和中介軟體,用來公開 SwaggerDocument 物件作為 JSON 端點。

  • Swashbuckle.AspNetCore.SwaggerGen:Swagger 產生器,可直接從您的路由、控制器和模型建置 SwaggerDocument 物件。 它通常會結合 Swagger 端點中介軟體,以便自動公開 Swagger JSON。

  • Swashbuckle.AspNetCore.SwaggerUI:Swagger UI 工具的內嵌版本。 它可解譯 Swagger JSON 來建置描述 Web API 功能的可自訂豐富體驗。 其中包括公用方法的內建測試載入器。

套件安裝

可使用下列方法新增 Swashbuckle:

  • 從 [套件管理員主控台] 視窗中:

    • 移至 [檢視]>[其他視窗]>[套件管理員主控台]

    • 瀏覽至 TodoApi.csproj 檔案所在的目錄

    • 執行以下 命令:

      Install-Package Swashbuckle.AspNetCore -Version 5.6.3
      
  • 從 [管理 NuGet 套件] 對話方塊中:

    • 在 [方案總管]>[管理 NuGet 套件] 中,以滑鼠右鍵按一下專案
    • 將 [套件來源] 設定為 "nuget.org"
    • 請確定已啟用 [包含發行前版本] 選項
    • 在搜尋方塊中輸入 "Swashbuckle.AspNetCore"
    • 從 [瀏覽] 索引標籤中選取最新的 "Swashbuckle.AspNetCore" 套件,並按一下 [安裝]

新增和設定 Swagger 中介軟體

將 Swagger 產生器新增至 Startup.ConfigureServices 方法中的服務集合:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt =>
        opt.UseInMemoryDatabase("TodoList"));
    services.AddControllers();

    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen();
}

Startup.Configure 方法中,啟用中介軟體來處理產生的 JSON 文件和 Swagger UI:

public void Configure(IApplicationBuilder app)
{
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.)
    app.UseSwaggerUI();

    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

注意

Swashbuckle 必須使用 MVC 的 Microsoft.AspNetCore.Mvc.ApiExplorer 來探索路由和端點。 如果專案呼叫 AddMvc,則會自動探索路由和端點。 呼叫 AddMvcCore 時,必須明確呼叫 AddApiExplorer 方法。 如需詳細資訊,請參閱 Swashbuckle、ApiExplorer 和 Routing

上述 UseSwaggerUI 方法呼叫會啟用 Swagger UI 工具的內嵌版本。 這取決於靜態檔案中間件。 如果以 .NET Framework 或 .NET Core 1.x 為目標,請將 Microsoft.AspNetCore.StaticFiles NuGet 套件新增至專案。

啟動應用程式,並巡覽至 http://localhost:<port>/swagger/v1/swagger.json。 描述端點的產生文件隨即出現,如 OpenAPI 規格 (openapi.json) 中所示。

您可以在 http://localhost:<port>/swagger 找到 Swagger UI。 透過 Swagger UI 探索 API,並將其併入其他程式。

提示

若要在應用程式的根目錄 (http://localhost:<port>/) 上提供 Swagger UI,請將 RoutePrefix 屬性設為空字串:

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    c.RoutePrefix = string.Empty;
});

若使用目錄搭配 IIS 或 反向 Proxy,請將 Swagger 端點設定為使用 ./ 前置詞的相對路徑。 例如: ./swagger/v1/swagger.json 。 使用 /swagger/v1/swagger.json 指示應用程式在 URL 的真實根目錄 (若已使用,請加上路由前置詞) 尋找 JSON 檔案。 例如,使用 http://localhost:<port>/<route_prefix>/swagger/v1/swagger.json 而不是 http://localhost:<port>/<virtual_directory>/<route_prefix>/swagger/v1/swagger.json

注意

根據預設,在 3.0 版的規格中 (正式名稱為 OpenAPI 規格),Swashbuckle 會產生並公開 Swagger JSON。 若要支援回溯相容性,您可以選擇改為以 2.0 格式公開 JSON。 對於目前支援 OpenAPI 2.0 版的 Microsoft Power Apps 和 Microsoft Flow 之類的整合來說,這個 2.0 格式很重要。 若要選擇使用 2.0 格式,請在 Startup.Configure 中設定 SerializeAsV2屬性:

public void Configure(IApplicationBuilder app)
{
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger(c =>
    {
        c.SerializeAsV2 = true;
    });

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

自訂和擴充

Swagger 提供用來記載物件模型和自訂 UI 以符合佈景主題的選項。

Startup 類別中,加入下列命名空間:

using System;
using System.Reflection;
using System.IO;

API 資訊與描述

傳遞至 AddSwaggerGen 方法的組態動作會新增作者、授權和描述等資訊:

Startup 類別中,匯入下列命名空間以使用 OpenApiInfo 類別:

using Microsoft.OpenApi.Models;

使用 OpenApiInfo 類別,修改顯示在 UI 中的資訊:

// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "ToDo API",
        Description = "A simple example ASP.NET Core Web API",
        TermsOfService = new Uri("https://example.com/terms"),
        Contact = new OpenApiContact
        {
            Name = "Shayne Boyer",
            Email = string.Empty,
            Url = new Uri("https://twitter.com/spboyer"),
        },
        License = new OpenApiLicense
        {
            Name = "Use under LICX",
            Url = new Uri("https://example.com/license"),
        }
    });
});

Swagger UI 會顯示版本資訊:

Swagger UI with version information: description, author, and see more link.

XML 註解

XML 註解可以使用下列方式啟用:

  • 在 [方案總管] 中以滑鼠右鍵按一下專案,然後選取 Edit <project_name>.csproj
  • 將醒目提示的程式碼行手動新增至 .csproj 檔案:
<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

啟用 XML 註解,可提供未記載之公用類型與成員的偵錯資訊。 未記載的類型和成員會以警告訊息表示。 例如,下列訊息指出警告碼 1591 的違規:

warning CS1591: Missing XML comment for publicly visible type or member 'TodoController.GetAll()'

在專案檔中定義要忽略的警告碼清單 (以分號分隔),即可隱藏警告。 將警告碼附加至 $(NoWarn); 也會套用 C# 預設值

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

若只要針對特定成員隱藏,請將程式碼放在 #pragma 警告前置處理器指示詞中。 針對不應該透過 API 文件公開的程式碼,此方法非常有用。在下列範例中,會針對整個 Program 類別忽略警告碼 CS1591。 會在類別定義結尾處還原強制執行的警告碼。 以逗號分隔清單指定多個警告碼。

namespace TodoApi
{
#pragma warning disable CS1591
    public class Program
    {
        public static void Main(string[] args) =>
            BuildWebHost(args).Run();

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
#pragma warning restore CS1591
}

設定 Swagger 以使用先前指示所產生的 XML 檔案。 對於 Linux 或非 Windows 作業系統,檔案名稱和路徑可以區分大小寫。 例如,TodoApi.XML 檔案在 Windows 上有效,但在 CentOS 上則無效。

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt =>
        opt.UseInMemoryDatabase("TodoList"));
    services.AddControllers();

    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "ToDo API",
            Description = "A simple example ASP.NET Core Web API",
            TermsOfService = new Uri("https://example.com/terms"),
            Contact = new OpenApiContact
            {
                Name = "Shayne Boyer",
                Email = string.Empty,
                Url = new Uri("https://twitter.com/spboyer"),
            },
            License = new OpenApiLicense
            {
                Name = "Use under LICX",
                Url = new Uri("https://example.com/license"),
            }
        });

        // Set the comments path for the Swagger JSON and UI.
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        c.IncludeXmlComments(xmlPath);
    });
}

在上述程式碼中,Reflection 用來建置與 Web API 專案名稱相符的 XML 檔案名稱。 AppContext.BaseDirectory 屬性用來建構 XML 檔案的路徑。 某些 Swagger 功能 (例如輸入參數的結構描述,或來自相對應屬性的 HTTP 方法和回應碼) 能在不使用 XML 文件檔案的情況下運作。 對於大部分的功能 (也就是方法摘要,以及參數和回應碼的描述) 而言,皆必須使用 XML 檔案。

透過在區段標題新增描述,對動作新增三斜線註解,可增強 Swagger UI。 在 Delete 動作上方新增 <summary> 元素:

/// <summary>
/// Deletes a specific TodoItem.
/// </summary>
/// <param name="id"></param>        
[HttpDelete("{id}")]
public IActionResult Delete(long id)
{
    var todo = _context.TodoItems.Find(id);

    if (todo == null)
    {
        return NotFound();
    }

    _context.TodoItems.Remove(todo);
    _context.SaveChanges();

    return NoContent();
}

Swagger UI 會顯示上述程式碼的 <summary> 項目的內部文字:

Swagger UI showing XML comment 'Deletes a specific TodoItem.' for the DELETE method.

UI 是由產生的 JSON 結構描述所驅動:

"delete": {
    "tags": [
        "Todo"
    ],
    "summary": "Deletes a specific TodoItem.",
    "operationId": "ApiTodoByIdDelete",
    "consumes": [],
    "produces": [],
    "parameters": [
        {
            "name": "id",
            "in": "path",
            "description": "",
            "required": true,
            "type": "integer",
            "format": "int64"
        }
    ],
    "responses": {
        "200": {
            "description": "Success"
        }
    }
}

請將 <remarks>Create 元素新增至 動作方法文件。 它會補充 <summary> 項目中指定的資訊,並提供更強固的 Swagger UI。 <remarks> 元素內容可以包含文字、JSON 或 XML。

/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Sample request:
///
///     POST /Todo
///     {
///        "id": 1,
///        "name": "Item1",
///        "isComplete": true
///     }
///
/// </remarks>
/// <param name="item"></param>
/// <returns>A newly created TodoItem</returns>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>            
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<TodoItem> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    _context.SaveChanges();

    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}

請注意使用這些額外註解的 UI 增強功能:

Swagger UI with additional comments shown.

資料註解

使用 System.ComponentModel.DataAnnotations 命名空間中找到的屬性來標記模型,以協助驅動 Swagger UI 元件。

[Required] 屬性 (attribute) 新增至 TodoItem 類別的 Name 屬性 (property):

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace TodoApi.Models
{
    public class TodoItem
    {
        public long Id { get; set; }

        [Required]
        public string Name { get; set; }

        [DefaultValue(false)]
        public bool IsComplete { get; set; }
    }
}

這個屬性的存在會變更 UI 行為,並改變基礎的 JSON 結構描述:

"definitions": {
    "TodoItem": {
        "required": [
            "name"
        ],
        "type": "object",
        "properties": {
            "id": {
                "format": "int64",
                "type": "integer"
            },
            "name": {
                "type": "string"
            },
            "isComplete": {
                "default": false,
                "type": "boolean"
            }
        }
    }
},

[Produces("application/json")] 屬性新增至 API 控制器。 其目的是要宣告控制器的動作支援回應內容類型為 application/json

[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
    private readonly TodoContext _context;

[回應內容類型] 下拉式清單會選取此內容類型,作為控制器 GET 動作的預設值:

Swagger UI with default response content type.

當 Web API 中的資料註釋使用量增加時,UI 和 API 說明頁面會變得更清楚且更有用。

描述回應類型

取用 Web API 的開發人員最關心的是傳回的內容:特別是回應類型和錯誤碼 (如果不是標準的話)。 回應類型和錯誤碼會在 XML 註解及資料註解中表示。

Create 動作在成功時會傳回 HTTP 201 狀態碼。 張貼的要求主體為 Null 時,會傳回 HTTP 400 狀態碼。 如果 Swagger UI 中沒有適當的文件,取用者便會缺乏對這些預期結果的了解。 在下列範例中新增強調顯示的那幾行來修正該問題:

/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Sample request:
///
///     POST /Todo
///     {
///        "id": 1,
///        "name": "Item1",
///        "isComplete": true
///     }
///
/// </remarks>
/// <param name="item"></param>
/// <returns>A newly created TodoItem</returns>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>            
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<TodoItem> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    _context.SaveChanges();

    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}

現在,Swagger UI 清楚記載了預期的 HTTP 回應碼:

Swagger UI showing POST Response Class description 'Returns the newly created Todo item' and '400 - If the item is null' for status code and reason under Response Messages.

在 ASP.NET Core 2.2 或更新版本中,慣例可作為使用 [ProducesResponseType] 明確裝飾個別動作的替代方案。 如需詳細資訊,請參閱使用 Web API 慣例

為了支援 [ProducesResponseType] 裝飾,Swashbuckle.AspNetCore.Annotations 套件提供的擴充功能,可啟用和擴充回應、結構描述和參數中繼資料。

自訂 UI

預設 UI 既可運作又能呈現。 不過,API 的文件頁面應該表示您的品牌或佈景主題。 設定 Swashbuckle 元件商標時,需要新增資源來處理靜態檔案,然後建置裝載這些檔案的資料夾結構。

如果以 .NET Framework 或 .NET Core 1.x 為目標,請將 Microsoft.AspNetCore.StaticFiles NuGet 套件新增至您的專案:

<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.0" />

如果以 .NET Core 2.x 為目標並使用中繼套件,則已安裝上述 NuGet 套件。

啟用靜態檔案中介軟體:

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles();

    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

若要插入其他 CSS 樣式表,請將它們新增至專案的 wwwroot 資料夾,並在中介軟體選項中指定相對路徑:

app.UseSwaggerUI(c =>
{
     c.InjectStylesheet("/swagger-ui/custom.css");
}

其他資源