Swashbuckle Swagger在NetCore 3.1中較NetCore 2.2使用的注意事項及入門

方案選擇

使用Web API時,瞭解其各類方法對開發人員來講多是一項挑戰。
Swagger也稱爲OpenAPI,解決了爲 Web API 生成有用文檔和幫助頁的問題。 它具備諸如交互式文檔、客戶端 SDK生成和API可發現性等優勢。css

Swashbuckle.AspNetCore 和 NSwag .NET Swagger 實現

Swashbuckle.AspNetCore

是一個開源項目,用於生成 ASP.NET Core Web API 的 Swagger 文檔。html

NSwag

是另外一個用於生成 Swagger 文檔並將 Swagger UI 或 ReDoc 集成到 ASP.NET Core Web API 中的開源項目。 此外,NSwag 還提供了爲 API 生成 C# 和 TypeScript 客戶端代碼的方法。json

什麼是Swagger/OpenAPI

Swagger是一個與語言無關的規範,用於描述REST API。 Swagger項目已捐贈給OpenAPI計劃,如今它被稱爲開放API。這兩個名稱可互換使用,但OpenAPI是首選。它容許計算機和人員瞭解服務的功能,而無需直接訪問實現(源代碼、網絡訪問、文檔)。其中一個目標是儘可能減小鏈接取消關聯的服務所需的工做量。 另外一個目標是減小準確記錄服務所需的時間。api

Swagger規範(swagger.json)

Swagger 流的核心是Swagger規範,默認狀況下是名爲swagger.json的文檔。 它由 Swagger工具鏈(或其第三方實現)根據你的服務生成。它描述了 API 的功能以及使用 HTTP 對其進行訪問的方式。 它驅動Swagger UI,並由工具鏈用來啓用發現和客戶端代碼生成。網絡

Swagger UI

Swagger UI提供了基於Web的UI,它使用生成的Swagger規範提供有關服務的信息。 Swashbuckle和NSwag均包含Swagger UI的嵌入式版本,所以可以使用中間件註冊調用將該嵌入式版本託管在ASP.NET Core 應用中。架構

背景知識

Swashbuckle 有三個主要組成部分:app

Swashbuckle.AspNetCore.Swagger

將 SwaggerDocument 對象公開爲 JSON 終結點的 Swagger 對象模型和中間件。工具

Swashbuckle.AspNetCore.SwaggerGen

從路由、控制器和模型直接生成 SwaggerDocument 對象的 Swagger 生成器。 它一般與 Swagger 終結點中間件結合,以自動公開 Swagger JSON。visual-studio

Swashbuckle.AspNetCore.SwaggerUI

Swagger UI 工具的嵌入式版本。 它解釋 Swagger JSON 以構建描述 Web API 功能的可自定義的豐富體驗。 它包括針對公共方法的內置測試工具。測試

在NetCore 3中安裝

Nuget 安裝:Swashbuckle.AspNetCore 建議大於等於5.0版本

將Swagger生成器添加到Startup.ConfigureServices方法中的服務集合中

NetCore 3.1中,原NetCore2.2中的Info已經升級爲OpenApiInfo

基礎版本

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

升級版本

主項目生成的地方記得勾選,生成XML,這個用於加強

// 註冊Swagger生成器,定義一個和多個Swagger文檔
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);
});

反射用於生成與 Web API 項目相匹配的 XML 文件名。 AppContext.BaseDirectory屬性用於構造 XML 文件的路徑。 一些 Swagger 功能(例如,輸入參數的架構,或各自屬性中的 HTTP 方法和響應代碼)無需使用 XML 文檔文件便可起做用。 對於大多數功能(即方法摘要以及參數說明和響應代碼說明),必須使用 XML 文件。

Startup.Configure方法中,啓用中間件爲生成的JSON文檔和Swagger UI提供服務

基礎版本

// 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");
});

升級版本

// 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");

    // 要在應用的根 (http://localhost:<port>/) 處提供 Swagger UI,請將 RoutePrefix 屬性設置爲空字符串:
    //c.RoutePrefix = string.Empty;

    // 要在應用的根 (http://localhost:<port>/) 處提供 Swagger UI,請將 RoutePrefix 屬性設置爲空字符串:
    c.RoutePrefix = "doc";
});

晉級寫法

接口增長描述註釋

/// <summary>
/// 獲取列表信息
/// </summary>
/// <returns></returns>
[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

Swagger UI 顯示上述代碼的<summary>元素的內部文本

接口增長示範說明

/// <summary>
/// 獲取列表信息
/// </summary>
/// <remarks>
/// 示例請求:
///
///     GET /Get
///     {
///        "id": 1,
///        "name": "Item1",
///        "isComplete": true
///     }
///
/// </remarks>
/// <returns></returns>
[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

元素添加到Get操做方法文檔。 它能夠補充

元素中指定的信息,並提供更可靠的 Swagger UI。 元素內容可包含文本、JSON 或 XML。

數據模型增長註釋

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; }
    }
}

使用System.ComponentModel.DataAnnotations命名空間中的屬性來標記模型,以幫助驅動Swagger UI組件。將[Required]屬性添加到TodoItem類的Name屬性。

申明控制器響應內容類型

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

[Produces("application/json")]屬性添加到API控制器。 這樣作的目的是聲明控制器的操做支持application/json的響應內容類型。

申明控制動做響應類型

/// <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);
}

使用Web API的開發人員最關心的問題是返回的內容,特別是響應類型和錯誤代碼(若是不標準)。 在 XML註釋和數據註釋中表示響應類型和錯誤代碼。
Create 操做成功後返回 HTTP 201 狀態代碼。 發佈的請求正文爲 NULL 時,將返回 HTTP 400 狀態代碼。 若是 Swagger UI 中沒有提供合適的文檔,那麼使用者會缺乏對這些預期結果的瞭解。

自定義私有品牌UI

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

API 文檔頁應表明品牌或主題。 將 Swashbuckle 組件標記爲須要添加資源以提供靜態文件,並構建文件夾結構以託管這些文件。

從 Swagger UI GitHub 存儲庫中獲取 dist 文件夾的內容。 此文件夾包含 Swagger UI 頁必需的資產。
建立 wwwroot/swagger/ui 文件夾,而後將 dist 文件夾的內容複製到其中 。
使用如下 CSS 在 wwwroot/swagger/ui 中建立 custom.css 文件,以自定義頁面標題

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

引用其餘 CSS 文件後,引用「ui」文件夾內 index.html 文件中的 custom.css :

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

引用資源

Swashbuckle 和 ASP.NET Core 入門

相關文章
相關標籤/搜索