WebApi生成在线API文档--Swagger
1.前言
1.1 SwaggerUI
SwaggerUI 是一个简单的Restful API 测试和文档工具。简单、漂亮、易用(官方demo)。通过读取JSON 配置显示API. 项目本身仅仅也只依赖一些 html,css.js静态文件. 你可以几乎放在任何Web容器上使用。
1.2 Swashbuckle
Swashbuckle 是.NET类库,可以将WebAPI所有开放的控制器方法生成对应SwaggerUI的JSON配置。再通过SwaggerUI 显示出来。类库中已经包含SwaggerUI 。所以不需要额外安装。
2.快速开始
- 创建项目 OnlineAPI来封装百度音乐服务(示例下载) ,通过API可以搜索、获取音乐的信息和播放连接。
我尽量删除一些我们demo中不会用到的一些文件,使其看上去比较简洁。

WebAPI 安装 Swashbuckle
Install-Package Swashbuckle代码注释生成文档说明。
Swashbuckle 是通过生成的XML文件来读取注释的,生成 SwaggerUI,JSON 配置中的说明的。
安装时会在项目目录 App_Start 文件夹下生成一个 SwaggerConfig.cs 配置文件,用于配置 SwaggerUI 相关展示行为的。如图:

- 将配置文件大概99行注释去掉并修改为
c.IncludeXmlComments(GetXmlCommentsPath(thisAssembly.GetName().Name));
并在当前类中添加一个方法
/// <summary>
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
protected static string GetXmlCommentsPath(string name)
{
return string.Format(@"{0}\bin\{1}.XML", AppDomain.CurrentDomain.BaseDirectory, name);
}紧接着你在此Web项目属性生成选卡中勾选 “XML 文档文件”,编译过程中生成类库的注释文件

- 添加百度音乐 3个API

- 访问
http://<youhost>/swagger/ui/index,最终显示效果

- 我们通过API 测试API 是否成功运行

3.添加自定义HTTP Header
在开发移动端 API时常常需要验证权限,验证参数放在Http请求头中是再好不过了。WebAPI配合过滤器验证权限即可
首先我们需要创建一个 IOperationFilter 接口的类。IOperationFilter
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using System.Web.Http.Filters;
using Swashbuckle.Swagger;
namespace OnlineAPI.Utility
{
public class HttpHeaderFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null) operation.parameters = new List<Parameter>();
var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
//判断是否添加权限过滤器
var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Instance).Any(filter => filter is IAuthorizationFilter);
//判断是否允许匿名方法
var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (isAuthorized && !allowAnonymous)
{
operation.parameters.Add(new Parameter
{
name = "access-key",
@in = "header",
description = "用户访问Key",
required = false,
type = "string"
});
}
}
}
}
在 SwaggerConfig.cs 的 EnableSwagger 配置匿名方法类添加一行注册代码
c.OperationFilter<HttpHeaderFilter>();
添加Web权限过滤器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using Newtonsoft.Json;
namespace OnlineAPI.Utility
{
/// <summary>
///
/// </summary>
public class AccessKeyAttribute : AuthorizeAttribute
{
/// <summary>
/// 权限验证
/// </summary>
/// <param name="actionContext"></param>
/// <returns></returns>
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var request = actionContext.Request;
if (request.Headers.Contains("access-key"))
{
var accessKey = request.Headers.GetValues("access-key").SingleOrDefault();
//TODO 验证Key
return accessKey == "123456789";
}
return false;
}
/// <summary>
/// 处理未授权的请求
/// </summary>
/// <param name="actionContext"></param>
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
var content = JsonConvert.SerializeObject(new {State = HttpStatusCode.Unauthorized});
actionContext.Response = new HttpResponseMessage
{
Content = new StringContent(content, Encoding.UTF8, "application/json"),
StatusCode = HttpStatusCode.Unauthorized
};
}
}
}
在你想要的ApiController 或者是 Action 添加过滤器
[AccessKey]
最终显示效果

4.显示上传文件参数
SwaggerUI 有上传文件的功能和添加自定义HTTP Header 做法类似,只是我们通过特殊的设置来标示API具有上传文件的功能
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Description;
using Swashbuckle.Swagger;
namespace OnlineAPI.Utility
{
/// <summary>
///
/// </summary>
public class UploadFilter : IOperationFilter
{
/// <summary>
/// 文件上传
/// </summary>
/// <param name="operation"></param>
/// <param name="schemaRegistry"></param>
/// <param name="apiDescription"></param>
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (!string.IsNullOrWhiteSpace(operation.summary) && operation.summary.Contains("upload"))
{
operation.consumes.Add("application/form-data");
operation.parameters.Add(new Parameter
{
name = "file",
@in = "formData",
required = true,
type = "file"
});
}
}
}
}
在 SwaggerConfig.cs 的 EnableSwagger 配置匿名方法类添加一行注册代码
c.OperationFilter<UploadFilter>();

API 文档展示效果

5.版本和资源
你可以通过下列连接获取相关说明。
Swashbuckle 项目地址:
https://github.com/domaindrivendev/Swashbuckle
swagger-ui 项目地址:
https://github.com/swagger-api/swagger-ui
swagger-ui 官网地址:
http://swagger.io/swagger-ui/
WebApi生成在线API文档--Swagger的更多相关文章
- 第十二节:WebApi自动生成在线Api文档的两种方式
一. WebApi自带生成api文档 1. 说明 通过观察,发现WebApi项目中Area文件夹下有一个HelpPage文件夹,如下图,该文件夹就是WebApi自带的生成Api的方式,如果该文件夹没了 ...
- 使用swagger来编写在线api文档
swagger是一个非常简单,强大的框架.快速上手,只需要引入jar包 , 使用注解就可以生成一个漂亮的在线api文档 pom.xml <dependency> <groupId&g ...
- Spring Boot 集成 Swagger 生成 RESTful API 文档
原文链接: Spring Boot 集成 Swagger 生成 RESTful API 文档 简介 Swagger 官网是这么描述它的:The Best APIs are Built with Swa ...
- 使用Swagger2Markup归档swagger生成的API文档
文章出处: http://blog.didispace.com/swagger2markup-asciidoc/ 说明 项目中使用Swagger之后,我们能够很轻松的管理API文档,并非常简单的模拟接 ...
- spring boot / cloud (三) 集成springfox-swagger2构建在线API文档
spring boot / cloud (三) 集成springfox-swagger2构建在线API文档 前言 不能同步更新API文档会有什么问题? 理想情况下,为所开发的服务编写接口文档,能提高与 ...
- Spring Boot学习笔记 - 整合Swagger2自动生成RESTful API文档
1.添加Swagger2依赖 在pom.xml中加入Swagger2的依赖 <!--swagger2--> <dependency> <groupId>io.spr ...
- Golang使用swaggo自动生成Restful API文档
#关于Swaggo 相信很多程序猿和我一样不喜欢写API文档.写代码多舒服,写文档不仅要花费大量的时间,有时候还不能做到面面具全.但API文档是必不可少的,相信其重要性就不用我说了,一份含糊的文档甚至 ...
- GhostDoc:生成.NET API文档的工具 (帮忙文档)
在 Sandcastle:生成.NET API文档的工具 (帮忙文档) 后提供另一个生成API文档的工具. 1) 准备工作 安装GhostDoc Proc. 收费的哦.... 这个工具的优势是不像 ...
- 使用jsdoc-toolkit来自动生成js api文档
近来前端组小盆友开发的类库越来越多,很多情况下彼此不知道写了些什么方法,为了更好的合作提高工作效率,找了个比较好的api文档生成方法.使用jsdoc-toolkit来自动生成js api文档. 一. ...
随机推荐
- python 写日志
简单配置 日志级别 级别 何时使用 DEBUG 详细信息,典型地调试问题时会感兴趣. INFO 证明事情按预期工作. WARNING 表明发生了一些意外,或者不久的将来会发生问题(如'磁盘满了').软 ...
- json & pickle 序列化
#!/usr/bin/python # -*- coding: utf-8 -*- # 序列化: 例如把字典写进文件 info = { 'name': 'alex', 'age': 22 } f = ...
- Java中能否利用函数参数来返回值
转自https://blog.csdn.net/da_da_xiong/article/details/70039532 我们在写代码时通常会遇到一种情况,就是我们可能希望在一个函数操作完成后返回两个 ...
- 解锁 vmware esxi 6.7 并安装 mac os 10.13
1.安装 esxi 6.7 2.下载 unlocker 2.1.1.zip 3.上传 unlocker 2.1.1.zip esxi的磁盘中 4.开启esxi的ssh登录 5.使用 ssh 登录 es ...
- BZOJ1854: [Scoi2010]游戏 二分图
很早之前写的题了,发现没有更博,想了想,更一发出来. Orz ljss 这是冬令营上的例题...之后,我推出来了一种时间复杂度没有问题,空间复杂度没有问题的方法,额(⊙o⊙)…和给出的正解不同,但是能 ...
- AngularJs 服务 广播
1, angularJs的服务有provider,Service, Factory. Factory是对Service的封装,Service是对Provider的封装. Provide的源码如下: f ...
- 深入理解Java虚拟机 第三章 垃圾收集器 笔记
1.1 垃圾收集器 垃圾收集器是内存回收的具体实现.以下讨论的收集器是基于JDK1.7Update14之后的HotSpot虚拟机.这个虚拟机包含的所有收集器有: 上图展示了7种作用于不同分代的收集 ...
- sql中1=1的and和or问题
SELECT * FROM mentor_teacher WHERE 1 = 1 AND status = ? limit 0, 10 sql语句中如果有1=1的问题, 那么,如果是and并且的关 ...
- Redis持久化方式的选择
本文将介绍Redis持久化的两种方式:快照持久化和AOF持久化,并对两种方法进行分析和对比,方便在实际中做出选择. 持久化 什么是持久化 Redis所有数据保存在内存中,对数据的更新将异步地保存到磁盘 ...
- Apache Mina -2
我们可以了解到 mina是个异步通信框架,一般使用场景是服务端开发,长连接.异步通信使用mina是及其方便的.不多说,看例子. 本次mina 使用的例子是使用maven构建的,过程中需要用到的jar包 ...