Swagger 生成 ASP.NET Web API
使用 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
Swagger 生成 ASP.NET Web API的更多相关文章
- ASP.NET Core 中文文档 第二章 指南 (09) 使用 Swagger 生成 ASP.NET Web API 在线帮助测试文档
原文:ASP.NET Web API Help Pages using Swagger 作者:Shayne Boyer 翻译:谢炀(kiler) 翻译:许登洋(Seay) 对于开发人员来说,构建一个消 ...
- ASP.NET Web API 中使用 swagger 来管理 API 文档
本文以 ASP.NET Web API 为后台框架,利用 EF6 连接 postgreSQL 数据库,使用 swagger 来生成 REST APIs文档.文章分二个部分,第一部分主要讲如何用 EF6 ...
- ASP.NET Web API 使用Swagger
ASP.NET Web API 使用Swagger使用笔记 最近换了工作,其中Webapi这块没有文档,之前有了解过Swagger借此机会好好整理下常用的地方分享给有需要的小伙伴. 概述: 1.s ...
- ASP.NET Web API从注释生成帮助文档
默认情况下,ASP.NET Web API不从Controller的注释中生成帮助文档.如果要将注释作为Web API帮助文档的一部分,比如在帮助文档的Description栏目中显示方法注释中的su ...
- ASP.NET Web API 文件產生器 - 使用 Swagger
转帖:http://kevintsengtw.blogspot.hk/2015/12/aspnet-web-api-swagger.html Swagger 是一套 API 互動文件產生器,使用 HT ...
- Asp.Net Web Api中使用Swagger
关于swagger 设计是API开发的基础.Swagger使API设计变得轻而易举,为开发人员.架构师和产品所有者提供了易于使用的工具. 官方网址:https://swagger.io/solutio ...
- ASP.NET Web API根据代码注释生成Help文档
使用Visual Studio新建一个ASP.NET Web API项目,直接运行,查看Help文档可以看到如下的API帮助说明 如何在Description中显示描述. 1. 打开Controlle ...
- 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用
由于ASP.NET Web API具有与ASP.NET MVC类似的编程方式,再加上目前市面上专门介绍ASP.NET Web API 的书籍少之又少(我们看到的相关内容往往是某本介绍ASP.NET M ...
- ASP.NET Web API Model-ActionBinding
ASP.NET Web API Model-ActionBinding 前言 前面的几个篇幅把Model部分的知识点划分成一个个的模块来讲解,而在控制器执行过程中分为好多个过程,对于控制器执行过程(一 ...
随机推荐
- 《SDN核心技术剖析和实战指南》2.3 OF-CONFIG配置管理协议小结
OpenFlow协议定义了交换机和控制器交换数据的方式和规范,但并没有定义如何配置和管理必需的网络参数和网络资源,OF-CONFIG的提出就是为了对OpenFlow提供配置管理支持.如下图所示,OF- ...
- Java类加载器深入理解
本篇文章主要是详细写一下个人对Java ClassLoader的理解. 首先回顾一下,java虚拟机载入java类的步骤:java文件经过编译器编译后变成字节码文件(.class文件),类加载器(Cl ...
- MVC中各类文件
sln:解决方案文件,为解决方案资源管理器提供显示管理文件的图形接口所需的信息. .csproj:项目文件,创建应用程序所需的引用.数据连接.文件夹和文件的信息. .aspx:Web 窗体页由两部分组 ...
- 12、ERP设计之 系统基础管理(BS)- 模块与菜单的关联
ShareERP2013-10-03 模块:具有功能设计.权限绑定,链接用户菜单与系统的重要桥梁. 菜单:是用于显示与用户交互的重要入口,更是导航系统的舵手,所以它的设计直接影响到用户体验. 菜单可能 ...
- jQuery表单验证以及将表单序列化为json对象小练习
jquery表单验证(非实时验证),同时,将表单序列化为json对象提交表单. <!DOCTYPE html> <html lang="en"> <h ...
- Oracle sqlplus 语法
目录: 0. FREFACE 1. 执行一个SQL脚本文件 2. 对当前的输入进行编辑 3. 重新运行上一次运行的sql语句 4. 将显示的内容输出到指定文件 5. 关闭spool输出 6.显示一个表 ...
- wxPython学习笔记(二)
如何创建和使用一个应用程序对象? 任何wxPython应用程序都需要一个应用程序对象.这个应用程序对象必须是类wx.App或其定制的子类的一个实例.应用程序对象的主要目的是管理幕后的主事件循环. 父类 ...
- 2016 cocoapods的安装和使用以及版本升级遇到的问题
一.CocoaPods是什么? CocoaPods是一个负责管理iOS项目中第三方开源库的工具.CocoaPods的项目源码在Github上管理.该项目开始于2011年8月12日,在这两年多的时间里, ...
- 【AngularJS入门】用ng-repeat指令实现循环输出
循环输出列表很多项目在web服务端做,前端做好模版后后端写jsp代码,双方需要紧密合作,分清责任.有些项目由后端提供restful方法,前端用ajax调用自己循环,这种一般是大把的jquery拼字符串 ...
- XML自己定义检查器语法+约束(1)
每次使用它检查xml文件时,仅仅需改动xmldoc.load("xml文件名称");中的文件名称,然后将该文件放在浏览器中执行就可以. 依据浏览器弹出的对话框进行推断自己写的xml ...