相关文章推荐
个性的豆浆  ·  Spring Security ...·  1 年前    · 
八块腹肌的柠檬  ·  window.opener.postmess ...·  2 年前    · 

.NET 9 或更新版本中無法使用 Swashbuckle。 如需替代方案,請參閱 ASP.NET Core API 應用程式中的 OpenAPI 支援概觀

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:

builder.Services.AddSwaggerGen();

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

Program.cs 中亦啟用中介軟體以服務生成的 JSON 文件和 Swagger UI。

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 屬性設為空字串:

if (builder.Environment.IsDevelopment())
    app.UseSwaggerUI(options => // UseSwaggerUI is called only in Development.
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
        options.RoutePrefix = string.Empty;

若使用目錄搭配 IIS 或反向代理,請將 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

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

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 會顯示版本資訊:

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

    GenerateDocumentationFile 新增至 .csproj 檔案:

    <PropertyGroup>
      <GenerateDocumentationFile>true</GenerateDocumentationFile>
    </PropertyGroup>
    

    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 warning 前置處理器指示詞中。 針對不應該透過 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 上有效,但在 Ubuntu 上無效。

    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 的區段標題中新增描述以增強其功能。 在 <動作上方新增一個 > 元素。

    /// <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> 項目的內部文字:

    請將 < 動作方法文件。 它會補充 <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 增強功能:

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

    [Required] 屬性新增至 Name 屬性的 TodoItem 類別:

    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 動作的預設值:

    當 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 回應碼:

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

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

    自訂 UI

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

    啟用靜態檔案中介軟體:

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

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

    if (app.Environment.IsDevelopment())
        app.UseSwaggerUI(options => // UseSwaggerUI is called only in Development.
            options.InjectStylesheet("/swagger-ui/custom.css");
                  檢視或下載範例程式碼 \(英文\) (如何下載)
                  使用 Swagger 文件改善 API 的開發人員體驗
                  Swashbuckle.AspNetCore.SwaggerGen:Swagger 產生器,可直接從您的路由、控制器和模型建置 SwaggerDocument 物件。 它通常會結合 Swagger 端點中介軟體,以便自動公開 Swagger JSON。

    Swashbuckle.AspNetCore.SwaggerUI:Swagger UI 工具的內嵌版本。 它可以解譯 Swagger JSON,建置豐富、可自訂的 Web API 功能描述體驗。 它包含公用方法的內建測試工具。

    可以透過下列方法新增 Swashbuckle:

    新增和設定 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, IWebHostEnvironment env)
        if (env.IsDevelopment())
            // 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 屬性設為空字串:

    // // UseSwaggerUI Protected by if (env.IsDevelopment())
    app.UseSwaggerUI(c => // UseSwaggerUI Protected by if (env.IsDevelopment())
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        c.RoutePrefix = string.Empty;
    

    若使用目錄搭配 IIS 或反向代理,請將 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

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

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        if (env.IsDevelopment())
            // 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.
            // UseSwaggerUI is called only in Development.
            app.UseSwaggerUI(c => // UseSwaggerUI Protected by if (env.IsDevelopment())
                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 會顯示版本資訊:

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

    將醒目的行手動新增至 .csproj 檔案:

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

    將醒目的行手動新增至 .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 warning 前置處理器指示詞中。 針對不應該透過 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 上有效,但在 Ubuntu 上無效。

    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 的區段標題中新增描述以增強其功能。 在 <動作上方新增一個 > 元素。

    /// <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> 項目的內部文字:

    "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"

    請將 < 動作方法文件。 它會補充 <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 增強功能:

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

    [Required] 屬性新增至 Name 屬性的 TodoItem 類別:

    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 動作的預設值:

    當 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 回應碼:

    在 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.1.1" />
    

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

    啟用靜態檔案中介軟體:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        app.UseStaticFiles();
        if (env.IsDevelopment())
            // 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 => // UseSwaggerUI Protected by if (env.IsDevelopment())
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        app.UseRouting();
        app.UseEndpoints(endpoints =>
            endpoints.MapControllers();
    

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

    if (env.IsDevelopment())
        app.UseSwaggerUI(c =>
            c.InjectStylesheet("/swagger-ui/custom.css");
                  使用 Swagger 文件改善 API 的開發人員體驗