Swashbuckle 與 ASP.NET Core 使用者入門Get started with Swashbuckle and ASP.NET Core

Shayne BoyerScott Addie 提供By Shayne Boyer and Scott Addie

檢視或下載範例程式碼 (英文) (如何下載)View or download sample code (how to download)

Swashbuckle 有三個主要元件:There are three main components to Swashbuckle:

  • Swashbuckle.AspNetCore.Swagger:Swagger 物件模型和中介軟體,用來公開 SwaggerDocument 物件作為 JSON 端點。Swashbuckle.AspNetCore.Swagger: a Swagger object model and middleware to expose SwaggerDocument objects as JSON endpoints.

  • Swashbuckle.AspNetCore.SwaggerGen:Swagger 產生器,可直接從您的路由、控制器和模型建置 SwaggerDocument 物件。Swashbuckle.AspNetCore.SwaggerGen: a Swagger generator that builds SwaggerDocument objects directly from your routes, controllers, and models. 它通常會結合 Swagger 端點中介軟體,以便自動公開 Swagger JSON。It's typically combined with the Swagger endpoint middleware to automatically expose Swagger JSON.

  • Swashbuckle.AspNetCore.SwaggerUI:Swagger UI 工具的內嵌版本。Swashbuckle.AspNetCore.SwaggerUI: an embedded version of the Swagger UI tool. 它可解譯 Swagger JSON 來建置描述 Web API 功能的可自訂豐富體驗。It interprets Swagger JSON to build a rich, customizable experience for describing the web API functionality. 它包含公用方法的內建測試載入器。It includes built-in test harnesses for the public methods.

套件安裝Package installation

可使用下列方法新增 Swashbuckle:Swashbuckle can be added with the following approaches:

  • 從 [套件管理員主控台] 視窗中:From the Package Manager Console window:

    • 移至 [檢視] > [其他視窗] > [套件管理員主控台]Go to View > Other Windows > Package Manager Console

    • 巡覽至 TodoApi.csproj 檔案所在目錄Navigate to the directory in which the TodoApi.csproj file exists

    • 執行下列命令:Execute the following command:

      Install-Package Swashbuckle.AspNetCore -Version 5.0.0-rc2
      
  • 從 [管理 NuGet 套件] 對話方塊中:From the Manage NuGet Packages dialog:

    • 在 [方案總管] > [管理 NuGet 套件] 中,以滑鼠右鍵按一下專案Right-click the project in Solution Explorer > Manage NuGet Packages
    • 將 [套件來源] 設定為 "nuget.org"Set the Package source to "nuget.org"
    • 請確定已啟用 [包含發行前版本] 選項Ensure the "Include prerelease" option is enabled
    • 在搜尋方塊中輸入 "Swashbuckle.AspNetCore"Enter "Swashbuckle.AspNetCore" in the search box
    • 從 [瀏覽] 索引標籤中選取最新的 "Swashbuckle.AspNetCore" 套件,並按一下 [安裝]Select the latest "Swashbuckle.AspNetCore" package from the Browse tab and click Install

新增和設定 Swagger 中介軟體Add and configure Swagger middleware

Startup 類別中,匯入下列命名空間以使用 OpenApiInfo 類別:In the Startup class, import the following namespace to use the OpenApiInfo class:

using Microsoft.OpenApi.Models;

將 Swagger 產生器新增至 Startup.ConfigureServices 方法中的服務集合:Add the Swagger generator to the services collection in the Startup.ConfigureServices method:

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

    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt =>
        opt.UseInMemoryDatabase("TodoList"));
    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });
}
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 { Title = "My API", Version = "v1" });
    });
}

Startup.Configure 方法中,啟用中介軟體為產生的 JSON 文件和 Swagger UI 提供服務:In the Startup.Configure method, enable the middleware for serving the generated JSON document and the 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.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    app.UseMvc();
}
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.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

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

上述 UseSwaggerUI 方法呼叫會啟用靜態檔案中介軟體The preceding UseSwaggerUI method call enables the Static File Middleware. 如果以 .NET Framework 或 .NET Core 1.x 為目標,請將 Microsoft.AspNetCore.StaticFiles NuGet 套件新增至專案。If targeting .NET Framework or .NET Core 1.x, add the Microsoft.AspNetCore.StaticFiles NuGet package to the project.

啟動應用程式,並巡覽至 http://localhost:<port>/swagger/v1/swagger.jsonLaunch the app, and navigate to http://localhost:<port>/swagger/v1/swagger.json. 描述端點的已產生文件隨即出現,如 Swagger 規格 (swagger.json) 中所示。The generated document describing the endpoints appears as shown in Swagger specification (swagger.json).

您可以在 http://localhost:<port>/swagger 找到 Swagger UI。The Swagger UI can be found at http://localhost:<port>/swagger. 透過 Swagger UI 探索 API,並將其併入其他程式。Explore the API via Swagger UI and incorporate it in other programs.

提示

若要在應用程式的根目錄 (http://localhost:<port>/) 上提供 Swagger UI,請將 RoutePrefix 屬性設為空字串:To serve the Swagger UI at the app's root (http://localhost:<port>/), set the RoutePrefix property to an empty string:

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

若使用目錄搭配 IIS 或 反向 Proxy,請將 Swagger 端點設定為使用 ./ 前置詞的相對路徑。If using directories with IIS or a reverse proxy, set the Swagger endpoint to a relative path using the ./ prefix. 例如: ./swagger/v1/swagger.jsonFor example, ./swagger/v1/swagger.json. 使用 /swagger/v1/swagger.json 指示應用程式在 URL 的真實根目錄 (若已使用,請加上路由前置詞) 尋找 JSON 檔案。Using /swagger/v1/swagger.json instructs the app to look for the JSON file at the true root of the URL (plus the route prefix, if used). 例如,使用 http://localhost:<port>/<route_prefix>/swagger/v1/swagger.json 而不是 http://localhost:<port>/<virtual_directory>/<route_prefix>/swagger/v1/swagger.jsonFor example, use http://localhost:<port>/<route_prefix>/swagger/v1/swagger.json instead of http://localhost:<port>/<virtual_directory>/<route_prefix>/swagger/v1/swagger.json.

自訂與擴充Customize and extend

Swagger 提供用來記載物件模型和自訂 UI 以符合佈景主題的選項。Swagger provides options for documenting the object model and customizing the UI to match your theme.

Startup 類別中,加入下列命名空間:In the Startup class, add the following namespaces:

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

API 資訊與描述API info and description

傳遞至 AddSwaggerGen 方法的組態動作會新增作者、授權和描述等資訊:The configuration action passed to the AddSwaggerGen method adds information such as the author, license, and description:

// 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 會顯示版本資訊:The Swagger UI displays the version's information:

含有版本資訊的 Swagger UI:描述、作者,以及查看更多連結

XML 註解XML comments

XML 註解可以使用下列方式啟用:XML comments can be enabled with the following approaches:

  • 以滑鼠右鍵按一下 [方案總管] 中的專案,然後選取 [編輯 <專案名稱>.csproj]。Right-click the project in Solution Explorer and select Edit <project_name>.csproj.
  • 將醒目提示的程式碼行手動新增至 .csproj 檔案:Manually add the highlighted lines to the .csproj file:
<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
  • 以滑鼠右鍵按一下 [方案總管] 中的專案,然後選取 [屬性]。Right-click the project in Solution Explorer and select Properties.
  • 核取 [組建] 索引標籤之 [輸出] 區段下方的 [XML 文件檔] 方塊。Check the XML documentation file box under the Output section of the Build tab.

啟用 XML 註解,可提供未記載之公用類型與成員的偵錯資訊。Enabling XML comments provides debug information for undocumented public types and members. 未記載的類型和成員會以警告訊息表示。Undocumented types and members are indicated by the warning message. 例如,下列訊息指出警告碼 1591 的違規:For example, the following message indicates a violation of warning code 1591:

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

在專案檔中定義要忽略的警告碼清單 (以分號分隔),即可隱藏警告。To suppress warnings project-wide, define a semicolon-delimited list of warning codes to ignore in the project file. 將警告碼附加至 $(NoWarn); 也會套用 C# 預設值Appending the warning codes to $(NoWarn); applies the C# default values too.

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
<PropertyGroup>
  <DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

若只要針對特定成員隱藏,請將程式碼放在 #pragma 警告前置處理器指示詞中。To suppress warnings only for specific members, enclose the code in #pragma warning preprocessor directives. 針對不應該透過 API 文件公開的程式碼,此方法非常有用。在下列範例中,會針對整個 Program 類別忽略警告碼 CS1591。This approach is useful for code that shouldn't be exposed via the API docs. In the following example, warning code CS1591 is ignored for the entire Program class. 會在類別定義結尾處還原強制執行的警告碼。Enforcement of the warning code is restored at the close of the class definition. 以逗號分隔清單指定多個警告碼。Specify multiple warning codes with a comma-delimited list.

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 檔案。Configure Swagger to use the XML file that's generated with the preceding instructions. 對於 Linux 或非 Windows 作業系統,檔案名稱和路徑可以區分大小寫。For Linux or non-Windows operating systems, file names and paths can be case-sensitive. 例如,TodoApi.XML 檔案在 Windows 上有效,但在 CentOS 上則無效。For example, a TodoApi.XML file is valid on Windows but not 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);
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt =>
        opt.UseInMemoryDatabase("TodoList"));
    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // 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);
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt =>
        opt.UseInMemoryDatabase("TodoList"));
    services.AddMvc();

    // 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);
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt =>
        opt.UseInMemoryDatabase("TodoList"));
    services.AddMvc();

    // 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.GetEntryAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        c.IncludeXmlComments(xmlPath);
    });
}

在上述程式碼中,Reflection 用來建置與 Web API 專案名稱相符的 XML 檔案名稱。In the preceding code, Reflection is used to build an XML file name matching that of the web API project. AppContext.BaseDirectory 屬性用來建構 XML 檔案的路徑。The AppContext.BaseDirectory property is used to construct a path to the XML file. 某些 Swagger 功能 (例如輸入參數的結構描述,或來自相對應屬性的 HTTP 方法和回應碼) 能在不使用 XML 文件檔案的情況下運作。Some Swagger features (for example, schemata of input parameters or HTTP methods and response codes from the respective attributes) work without the use of an XML documentation file. 對於大部分的功能 (也就是方法摘要,以及參數和回應碼的描述) 而言,皆必須使用 XML 檔案。For most features, namely method summaries and the descriptions of parameters and response codes, the use of an XML file is mandatory.

將三斜線註解新增至動作,即可透過將描述新增至區段標頭來增強 Swagger UI。Adding triple-slash comments to an action enhances the Swagger UI by adding the description to the section header. Delete 動作上方新增 <summary> 項目:Add a <summary> element above the Delete action:

/// <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> 項目的內部文字:The Swagger UI displays the inner text of the preceding code's <summary> element:

顯示 XML 註解 'Deletes a specific TodoItem.' 的 Swagger UI

UI 是由產生的 JSON 結構描述所驅動:The UI is driven by the generated JSON schema:

"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 動作方法文件。Add a <remarks> element to the Create action method documentation. 它會補充 <summary> 項目中指定的資訊,並提供更強固的 Swagger UI。It supplements information specified in the <summary> element and provides a more robust Swagger UI. <remarks> 項目內容可以包含文字、JSON 或 XML。The <remarks> element content can consist of text, JSON, or 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(typeof(TodoItem), 201)]
[ProducesResponseType(400)]
public IActionResult Create([FromBody] TodoItem item)
{
    if (item == null)
    {
        return BadRequest();
    }

    _context.TodoItems.Add(item);
    _context.SaveChanges();

    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}
/// <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(201)]
[ProducesResponseType(400)]
public ActionResult<TodoItem> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    _context.SaveChanges();

    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}
/// <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(201)]
[ProducesResponseType(400)]
public ActionResult<TodoItem> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    _context.SaveChanges();

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

請注意使用這些額外註解的 UI 增強功能:Notice the UI enhancements with these additional comments:

顯示額外註解的 Swagger UI

資料註解Data annotations

使用 System.ComponentModel.DataAnnotations 命名空間中找到的屬性來裝飾模型,可協助驅動 Swagger UI 元件。Decorate the model with attributes, found in the System.ComponentModel.DataAnnotations namespace, to help drive the Swagger UI components.

[Required] 屬性 (attribute) 新增至 TodoItem 類別的 Name 屬性 (property):Add the [Required] attribute to the Name property of the TodoItem class:

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 結構描述:The presence of this attribute changes the UI behavior and alters the underlying JSON schema:

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

[Produces("application/json")] 屬性新增至 API 控制器。Add the [Produces("application/json")] attribute to the API controller. 其目的是要宣告控制器的動作支援回應內容類型為 application/jsonIts purpose is to declare that the controller's actions support a response content type of application/json:

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

[回應內容類型] 下拉式清單會選取此內容類型,作為控制器 GET 動作的預設值:The Response Content Type drop-down selects this content type as the default for the controller's GET actions:

含有預設回應內容類型的 Swagger UI

當 Web API 中的資料註釋使用量增加時,UI 和 API 說明頁面會變得更清楚且更有用。As the usage of data annotations in the web API increases, the UI and API help pages become more descriptive and useful.

描述回應類型Describe response types

取用 Web API 的開發人員最關心的是傳回的內容 — 特別是回應類型和錯誤碼 (如果不是標準的話)。Developers consuming a web API are most concerned with what's returned—specifically response types and error codes (if not standard). 回應類型和錯誤碼會在 XML 註解及資料註解中表示。The response types and error codes are denoted in the XML comments and data annotations.

Create 動作在成功時會傳回 HTTP 201 狀態碼。The Create action returns an HTTP 201 status code on success. 張貼的要求主體為 Null 時,會傳回 HTTP 400 狀態碼。An HTTP 400 status code is returned when the posted request body is null. 如果 Swagger UI 中沒有適當的文件,取用者便會缺乏對這些預期結果的了解。Without proper documentation in the Swagger UI, the consumer lacks knowledge of these expected outcomes. 在下列範例中新增強調顯示的那幾行來修正該問題:Fix that problem by adding the highlighted lines in the following example:

/// <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(typeof(TodoItem), 201)]
[ProducesResponseType(400)]
public IActionResult Create([FromBody] TodoItem item)
{
    if (item == null)
    {
        return BadRequest();
    }

    _context.TodoItems.Add(item);
    _context.SaveChanges();

    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}
/// <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(201)]
[ProducesResponseType(400)]
public ActionResult<TodoItem> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    _context.SaveChanges();

    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}
/// <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(201)]
[ProducesResponseType(400)]
public ActionResult<TodoItem> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    _context.SaveChanges();

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

現在,Swagger UI 清楚記載了預期的 HTTP 回應碼:The Swagger UI now clearly documents the expected HTTP response codes:

顯示 POST 回應類別描述 'Returns the newly created Todo item',並針對回應訊息下方的狀態碼和原因顯示 '400 - If the item is null' 的 Swagger UI

在 ASP.NET Core 2.2 或更新版本中,慣例可作為使用 [ProducesResponseType] 明確裝飾個別動作的替代方案。In ASP.NET Core 2.2 or later, conventions can be used as an alternative to explicitly decorating individual actions with [ProducesResponseType]. 如需詳細資訊,請參閱 使用 Web API 慣例For more information, see 使用 Web API 慣例.

自訂 UICustomize the UI

股票 UI 既可運作又能呈現。The stock UI is both functional and presentable. 不過,API 的文件頁面應該表示您的品牌或佈景主題。However, API documentation pages should represent your brand or theme. 設定 Swashbuckle 元件商標時,需要新增資源來處理靜態檔案,然後建置裝載這些檔案的資料夾結構。Branding the Swashbuckle components requires adding the resources to serve static files and building the folder structure to host those files.

如果以 .NET Framework 或 .NET Core 1.x 為目標,請將 Microsoft.AspNetCore.StaticFiles NuGet 套件新增至您的專案:If targeting .NET Framework or .NET Core 1.x, add the Microsoft.AspNetCore.StaticFiles NuGet package to the project:

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

如果以 .NET Core 2.x 為目標並使用中繼套件,則已安裝上述 NuGet 套件。The preceding NuGet package is already installed if targeting .NET Core 2.x and using the metapackage.

啟用靜態檔案中介軟體:Enable Static File Middleware:

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.UseMvc();
}
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();
    });
}

Swagger UI GitHub 儲存機制中取得 dist 資料夾的內容。Acquire the contents of the dist folder from the Swagger UI GitHub repository. 此資料夾包含 Swagger UI 頁面所需的資產。This folder contains the necessary assets for the Swagger UI page.

建立 wwwroot/swagger/ui 資料夾,並將 dist 資料夾的內容複製到其中。Create a wwwroot/swagger/ui folder, and copy into it the contents of the dist folder.

使用下列 CSS 在 wwwroot/swagger/ui 中建立 custom.css 檔案,以自訂頁面標頭:Create a custom.css file, in wwwroot/swagger/ui, with the following CSS to customize the page header:

.swagger-ui .topbar {
    background-color: #000;
    border-bottom: 3px solid #547f00;
}

在 ui 資料夾內 index.html 檔案中的其他任何 CSS 檔案之後,參考 custom.cssReference custom.css in the index.html file inside ui folder, after any other CSS files:

<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="./swagger-ui.css">
<link rel="stylesheet" type="text/css" href="custom.css">

瀏覽至 http://localhost:<port>/swagger/ui/index.html 上的 index.html 頁面。Browse to the index.html page at http://localhost:<port>/swagger/ui/index.html. 在標頭的文字方塊中輸入 https://localhost:<port>/swagger/v1/swagger.json,然後按一下 [瀏覽] 按鈕。Enter https://localhost:<port>/swagger/v1/swagger.json in the header's textbox, and click the Explore button. 結果頁面如下所示:The resulting page looks as follows:

含有自訂標頭標題的 Swagger UI

您還可以透過此頁面進行更多功能。There's much more you can do with the page. 請在 Swagger UI GitHub 儲存機制中查看 UI 資源的完整功能。See the full capabilities for the UI resources at the Swagger UI GitHub repository.