ASP.NET Core 中文文件 第二章 指南 (09) 使用 Swagger 生成 ASP.NET Web API 線上幫助測試文件
對於開發人員來說,構建一個消費應用程式時去了解各種各樣的 API 是一個巨大的挑戰。
在你的 Web API 專案中使用 Swagger 的 .NET Core 封裝 Swashbuckle 可以幫助你建立良好的文件和幫助頁面。 Swashbuckle 可以通過修改 Startup.cs 作為一組 NuGet 包方便的加入專案。
- Swashbuckle 是一個開源專案,為使用 ASP.NET Core MVC 構建的 Web APIs 生成 Swagger 文件。
- Swagger 是一個機器可讀的 RESTful API 表現層,它可以支援互動式文件、客戶端 SDK 的生成和可被發現。
開始入門
Swashbuckle 有兩個核心的元件
- Swashbuckle.SwaggerGen : 提供生成描述物件、方法、返回型別等的 JSON Swagger 文件的功能。
- Swashbuckle.SwaggerUI : 是一個嵌入式版本的 Swagger UI 工具,使用 Swagger UI 強大的富文字表現形式來可定製化的來描述 Web API 的功能,並且包含內建的公共方法測試工具。
NuGet 包
你可以通過以下方式新增 Swashbuckle:
- 通過 Package Manager 控制檯:
Install-Package Swashbuckle -Pre
- 在 project.json
"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>
相關推薦
ASP.NET Core 中文文件 第二章 指南 (09) 使用 Swagger 生成 ASP.NET Web API 線上幫助測試文件
對於開發人員來說,構建一個消費應用程式時去了解各種各樣的 API 是一個巨大的挑戰。 在你的 Web API 專案中使用 Swagger 的 .NET Core 封裝 Swashbuckle 可以幫助你建立良好的文件和幫助頁面。 Swashbuckle 可以通過修改 Startup.cs 作為一組 NuGe
ASP.NET Core 中文文件 第二章 指南(1)用 Visual Studio Code 在 macOS 上建立首個 ASP.NET Core 應用程式
本文已更新,最後更新於2017年4月28日 聯絡我們: QQ Group: 436035237 (dotNet Core Studying Group) GitHub Repo: https://github.com/dotnetcore/aspnetcore-doc-cn/ 以下為老翻譯存檔 本節將
ASP.NET Core 中文文件 第二章 指南(2)用 Visual Studio 和 ASP.NET Core MVC 建立首個 Web API
HTTP 協議不僅僅提供網頁服務。它也是一個構建公開服務和資料 API 的強大平臺。HTTP 協議是簡單、靈活、無處不在的。幾乎你能想到的任何平臺上都有 HTTP 支援,所以 HTTP 服務能夠傳送到多種客戶端, 包括瀏覽器,移動裝置和傳統的桌面應用程式。 在本教程中,你將建立一個簡單的 Web API 來
ASP.NET Core 中文文件 第二章 指南(8) 使用 dotnet watch 開發 ASP.NET Core 應用程式
本文已更新,最後更新於2017年4月27日 以下為老翻譯存檔 介紹 dotnet watch 是一個開發階段在原始檔發生變動的情況下使用 dotnet 命令的工具。 當代碼發生變動的時候可以用來執行編譯,執行測試,或者釋出操作。 在本教程中,我們將使用一個現有的計算兩個數字之和以及乘積的 WebAp
ASP.NET Core 中文文件 第二章 指南(5) 在 Nano Server 上執行ASP.NET Core
注意:本教程使用 Windows Server Technical Preview 5 的預發行版本的 Nano Server 安裝選項。 你可以在虛擬硬碟映像中用來內部演示和評估,但不能在生產環境中使用該軟體。可通過 https://go.microsoft.com/fwlink/?LinkId=624
ASP.NET Core 中文文件 第二章 指南(3)用 Visual Studio 釋出一個 Azure 雲 Web 應用程式
設定開發環境 注意 如果你的機器之前任何依賴都沒有安裝過,SDK 的安裝時間將會超過30分鐘。 建立一個 Web 應用程式 在 Visual Studio 的 Start 頁面,點選 New Project。 另外,你也可以通過選單新建專案。點選 File > New > Proje
ASP.NET Core 中文文件 第二章 指南(4.10)檢查自動生成的Detail方法和Delete方法
開啟 Movie 控制器並檢視 Details 方法: // GET: Movies/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return No
ASP.NET Core 中文文件 第二章 指南(4.1)ASP.NET Core MVC 與 Visual Studio 入門
這篇教程將告訴你如何使用 Visual Studio 2015 構建一個 ASP.NET Core MVC Web 應用程式的基礎知識。 安裝 Visual Studio 和 .NET Core 安裝 Visual Studio Community 2015。選擇 Community 下載並執行預設安裝
ASP.NET Core 中文文件 第二章 指南(4.6)Controller 方法與檢視
我們已經初步的建立了一個 movie 應用程式,但是展示並不理想。我們不希望看到 release date 欄位顯示時間並且 ReleaseDate 應該是兩個單詞。 開啟 Models/Movie.cs 檔案並新增下面高亮的程式碼行: public class Movie { public in
ASP.NET Core 中文文件 第二章 指南(4.5)使用 SQL Server LocalDB
ApplicationDbContext 類負責連線資料庫並將 Movie 物件和資料記錄進行對映。 Startup.cs 檔案中,資料庫上下文是在 ConfigureServices 方法中用 Dependency Injection 容器進行註冊的。 // This method gets called
ASP.NET Core中使用GraphQL - 第二章 中介軟體
前文:ASP.NET Core中使用GraphQL - 第一章 Hello World 中介軟體 如果你熟悉ASP.NET Core的中介軟體,你可能會注意到之前的部落格中我們已經使用了一箇中間件, app.Run(async (context) => { var result =
體驗 ASP.NET Core 中的多語言支持(Localization)
lan expander -c blank 根據 body esp doc input 首先在 Startup 的 ConfigureServices 中添加 AddLocalization 與 AddViewLocalization 以及配置 RequestLocaliz
ASP.NET Core 2.0 : 四. _Layout與_ViewStart(轉)
src 新建 req app com mage blog 再次 重復 本章我們新建一個項目,並通過這個項目熟悉一下_Layout與_ViewStart以及它們的加載順序. ASP.NET Core 系列目錄 新建一個項目 首先, 文件->新建一個解決方案
ASP.NET Core 選項模式原始碼學習Options Configure(一)
前言 ASP.NET Core 後我們的配置變得更加輕量級了,在ASP.NET Core中,配置模型得到了顯著的擴充套件和增強,應用程式配置可以儲存在多環境變數配置中,appsettings.json使用者機密等 並可以通過應用程式中的相同介面輕鬆訪問,除此之外,ASP.NET中的新配置系統允許使用Opt
ASP.NET Core 選項模式原始碼學習Options IOptions(二)
前言 上一篇文章介紹IOptions的註冊,本章我們繼續往下看 IOptions IOptions是一個接口裡面只有一個Values屬性,該介面通過OptionsManager實現 public interface IOptions<out TOptions> where TOpt
ASP.NET Core 選項模式原始碼學習Options IOptionsMonitor(三)
前言 IOptionsMonitor 是一種單一示例服務,可隨時檢索當前選項值,這在單一例項依賴項中尤其有用。IOptionsMonitor用於檢索選項並管理TOption例項的選項通知, IOptionsMonitor 支援以下方案: 更改通知 命名選項 可過載配置 選擇性選項失效 (IOptions
Android官方技術文檔翻譯——Gradle 插件用戶指南(4)
庫項目 包含 doc 努力 時也 外部 插件 http name 近期趕項目,白天基本沒時間,僅僅有晚上在家的時候才幹看一看。昨天晚上僅僅翻譯完了第四章,今天就僅僅發第四章吧。 本文譯自Android官方技術文檔《Gradle Plugin User Guide》,
.net core 中後臺獲取前臺 數據(post)的方法
json字符串 序列化 convert pda pub poi ade 反序列化 stream [HttpPost] public async Task<JsonResult> EditPoint() { St
.Net Core 商城微服務項目系列(一):使用IdentityServer4構建基礎登錄驗證
tap .net core catch access 返回 ip) logging address fin 這裏第一次搭建,所以IdentityServer端比較簡單,後期再進行完善。 1.新建API項目MI.Service.Identity,NuGet引用Identity