使用 Swagger 生成 ASP.NET Web API 在線幫助測試文檔
原文:ASP.NET Web API Help Pages using Swagger
作者:Shayne Boyer
翻譯:謝煬(kiler)
翻譯:許登洋(Seay)
對於開發人員來說,構建一個消費應用程序時去了解各種各樣的 API 是一個巨大的挑戰。
在你的 Web API 項目中使用 Swagger 的 .NET Core 封裝 Swashbuckle 可以幫助你創建良好的文檔和幫助頁面。 Swashbuckle 可以通過修改 Startup.cs 作為一組 NuGet 包方便的加入項目。
- Swashbuckle 是一個開源項目,為使用 ASP.NET Core MVC 構建的 Web APIs 生成 Swagger 文檔。
- Swagger 是一個機器可讀的 RESTful API 表現層,它可以支持交互式文檔、客戶端 SDK 的生成和可被發現。
本教程基於 用 ASP.NET Core MVC 和 Visual Studio 創建你的第一個 Web API 文檔的例子構建。如果需要對應的代碼,在這里 https://github.com/aspnet/Docs/tree/master/aspnet/tutorials/first-web-api/sample 下載示例。
開始入門
Swashbuckle 有兩個核心的組件
- Swashbuckle.SwaggerGen : 提供生成描述對象、方法、返回類型等的 JSON Swagger 文檔的功能。
- Swashbuckle.SwaggerUI : 是一個嵌入式版本的 Swagger UI 工具,使用 Swagger UI 強大的富文本表現形式來可定制化的來描述 Web API 的功能,並且包含內置的公共方法測試工具。
NuGet 包
你可以通過以下方式添加 Swashbuckle:
-
通過 Package Manager 控制台:
復制代碼Install-Package Swashbuckle -Pre -
在 project.json 中添加 Swashbuckle:
復制代碼"Swashbuckle": "6.0.0-beta902" - 在 Visual Studio 中:
- 右擊你的項目 Solution Explorer > Manage NuGet Packages
- 在搜索框中輸入 Swashbuckle
- 點擊 “Include prerelease”
- 設置 Package source 為 nuget.org
- 點擊 Swashbuckle 包並點擊 Install
在中間件中添加並配置 Swagger
在 Configure 方法里面把 SwaggerGen 添加到 services 集合,並且在 ConfigureServices 方法中,允許中間件提供和服務生成 JSON 文檔以及 SwaggerUI。
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddLogging(); // Add our repository type services.AddSingleton<ITodoRepository, TodoRepository>(); // Inject an implementation of ISwaggerProvider with defaulted settings applied services.AddSwaggerGen(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseMvcWithDefaultRoute(); // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUi(); }
在 Visual Studio 中, 點擊 ^F5 啟動應用程序並導航到 http://localhost:<random_port>/swagger/v1/swagger.json 頁面可以看成生成的終端描述文檔。
提示
Microsoft Edge,Google Chrome 以及 Firefox 原生支持顯示 JSON 文檔。 Chrome 的擴展會格式化文檔使其更易於閱讀。 下面的例子是簡化版的。
{
"swagger": "2.0", "info": { "version": "v1", "title": "API V1" }, "basePath": "/", "paths": { "/api/Todo": { "get": { "tags": [ "Todo" ], "operationId": "ApiTodoGet", "consumes": [], "produces": [ "text/plain", "application/json", "text/json" ], "responses": { "200": { "description": "OK", "schema": { "type": "array", "items": { "$ref": "#/definitions/TodoItem" } } } }, "deprecated": false }, "post": { ... } }, "/api/Todo/{id}": { "get": { ... }, "put": { ... }, "delete": { ... }, "definitions": { "TodoItem": { "type": "object", "properties": { "key": { "type": "string" }, "name": { "type": "string" }, "isComplete": { "type": "boolean" } } } }, "securityDefinitions": {} }
這個文檔用來驅動 Swagger UI,可以通過訪問 http://localhost:<random_port>/swagger/ui 頁面來查看。
所有的 ToDo controller 的方法都是可以在 UI 上面進行測試。點擊方法可以展開對應的區域,輸入所需的參數並且點擊 “Try it out!” 。
自定義與可擴展性
Swagger 不僅是顯示 API 的一個簡單方法,而且有可選項:文檔對象模型,以及自定義交互 UI 來滿足你的視覺感受或者設計語言。
API 信息和描述
ConfigureSwaggerGen 方法用來添加文檔信息。例如:作者,版權,描述。
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info { Version = "v1", Title = "ToDo API", Description = "A simple example ASP.NET Core Web API", TermsOfService = "None", Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "http://twitter.com/spboyer"}, License = new License { Name = "Use under LICX", Url = "http://url.com" } }); });
下圖展示了 Swagger UI 顯示添加的版本信息。
XML 注釋
為了啟用 XML 注釋, 在 Visual Studio 中右擊項目並且選擇 Properties 在 Output Settings 區域下面點擊 XML Documentation file 。
另外,你也可以通過在 project.json 中設置 “xmlDoc”: true 來啟用 XML 注釋。
"buildOptions": { "emitEntryPoint": true, "preserveCompilationContext": true, "xmlDoc": true },
配置 Swagger 使用生成的 XML 文件。
提示
對於 Linux 或者 非 Windows 操作系統,文件名和路徑是大小寫敏感的。 所以本例中的ToDoApi.XML在 Windows 上可以找到但是 CentOS 就無法找到。
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddLogging(); // Add our repository type. services.AddSingleton<ITodoRepository, TodoRepository>(); // Inject an implementation of ISwaggerProvider with defaulted settings applied. services.AddSwaggerGen(); // Add the detail information for the API. services.ConfigureSwaggerGen(options => { options.SingleApiVersion(new Info { Version = "v1", Title = "ToDo API", Description = "A simple example ASP.NET Core Web API", TermsOfService = "None", Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "http://twitter.com/spboyer"}, License = new License { Name = "Use under LICX", Url = "http://url.com" } }); //Determine base path for the application. var basePath = PlatformServices.Default.Application.ApplicationBasePath; //Set the comments path for the swagger json and ui. options.IncludeXmlComments(basePath + "\\TodoApi.xml"); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUi(); }
在上面的代碼中,ApplicationBasePath 獲取到應用程序的根路徑,是需要設置 XML 注釋文件的完整路徑。 TodoApi.xml 僅適用於本例,生成的XML注釋文件的名稱是基於你的應用程序名稱。
為方法添加的三斜線注釋(C# 文檔注釋格式)文字會作為描述顯示在 Swagger UI 對應方法的頭區域。
/// <summary> /// Deletes a specific TodoItem. /// </summary> /// <param name="id"></param> [HttpDelete("{id}")] public void Delete(string id) { TodoItems.Remove(id); }

請注意,UI 是由生成的 JSON 文件驅動的,這些注釋也會包含在文件中。
"delete": { "tags": [ "Todo" ], "summary": "Deletes a specific TodoItem", "operationId": "ApiTodoByIdDelete", "consumes": [], "produces": [], "parameters": [ { "name": "id", "in": "path", "description": "", "required": true, "type": "string" } ], "responses": { "204": { "description": "No Content" } }, "deprecated": false }
這是一個更強大的例子,加入 <remarks /> 那里面的內容可以是文字或添加的 JSON 或 XML 對象的方法為進一步描述方法文檔而服務。
/// <summary> /// Creates a TodoItem. /// </summary> /// <remarks> /// Note that the key is a GUID and not an integer. /// /// POST /Todo /// { /// "key": "0e7ad584-7788-4ab1-95a6-ca0a5b444cbb", /// "name": "Item1", /// "isComplete": true /// } /// /// </remarks> /// <param name="item"></param> /// <returns>New Created Todo Item</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(typeof(TodoItem), 400)] public IActionResult Create([FromBody, Required] TodoItem item) { if (item == null) { return BadRequest(); } TodoItems.Add(item); return CreatedAtRoute("GetTodo", new { id = item.Key }, item); }
請注意下面是這些附加注釋的在用戶界面的增強效果。
DataAnnotations
你可以使用 System.ComponentModel.DataAnnotations 來標注 API controller ,幫助驅動 Swagger UI 組件。
在 TodoItem 類的 Name 屬性上添加 [Required] 標注會改變 UI 中的模型架構信息。[Produces("application/json"] ,正則表達式驗證器將更進一步細化生成頁面傳遞的詳細信息。代碼中使用的元數據信息越多 API 幫助頁面上的描述信息也會越多。
using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace TodoApi.Models { public class TodoItem { public string Key { get; set; } [Required] public string Name { get; set; } [DefaultValue(false)] public bool IsComplete { get; set; } } }
描述響應類型
API 使用開發者最關心的東西是的返回結果;具體響應類型,錯誤代碼(如果不是標准錯誤碼)。這些都在 XML 注釋 和 DataAnnotations 中處理。
以 Create() 方法為例,目前它僅僅返回 “201 Created” 默認響應。如果數據實際創建了或者 POST 正文沒有傳遞數據返回 “204 No Content” 錯誤,這是理所當然的。但是,如果沒有文檔知道它的存在或者存在任何其他響應,則可以通過添加下面的代碼段是修復這個問題。
/// <summary> /// Creates a TodoItem. /// </summary> /// <remarks> /// Note that the key is a GUID and not an integer. /// /// POST /Todo /// { /// "key": "0e7ad584-7788-4ab1-95a6-ca0a5b444cbb", /// "name": "Item1", /// "isComplete": true /// } /// /// </remarks> /// <param name="item"></param> /// <returns>New Created Todo Item</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(typeof(TodoItem), 400)] public IActionResult Create([FromBody, Required] TodoItem item) { if (item == null) { return BadRequest(); } TodoItems.Add(item); return CreatedAtRoute("GetTodo", new { id = item.Key }, item); }

自定義 UI
stock UI 是一個非常實用的展示方案,如果你想在生成 API 文檔頁面的時候想把你的標題做的更好看點。
完成與 Swashbuckle 組件相關的任務很簡單,但服務需要添加的資源來通常不會被包含在 Web API 項目中,所以必須建立對應的的文件夾結構來承載這些靜態資源文件。
在項目中添加 "Microsoft.AspNetCore.StaticFiles": "1.0.0-*" NuGet 包。
在中間件中啟用 static files 服務。
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUi(); }
從 Github repository 上獲取 Swagger UI 頁面所需的 index.html 核心文件,把他放到 wwwroot/swagger/ui 目錄下,並在在同一個文件夾創建一個新的 custom.css 文件。

在 index.html 文件中引用 custom.css 。
<link href='custom.css' media='screen' rel='stylesheet' type='text/css' />
下面的 CSS 提供了一個自定義頁面標題的簡單的示例。
custom.css 文件
.swagger-section #header { border-bottom: 1px solid #000000; font-style: normal; font-weight: 400; font-family: "Segoe UI Light","Segoe WP Light","Segoe UI","Segoe WP",Tahoma,Arial,sans-serif; background-color: black; } .swagger-section #header h1 { text-align: center; font-size: 20px; color: white; }
index.html 正文
<body class="swagger-section"> <div id="header"> <h1>ToDo API Documentation</h1> </div> <div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div> <div id="swagger-ui-container" class="swagger-ui-wrap"></div> </body>

你可以在這個頁面有更多改進的東西,請在 Swagger UI Github repository 參閱完整的 UI 資源。
dotNet Core Studying Group:436035237
