SwaggerUI 是一個簡單的Restful API 測試和文檔工具。簡單、漂亮、易用(官方demo)。經過讀取JSON 配置顯示API. 項目自己僅僅也只依賴一些 html,css.js靜態文件. 你能夠幾乎放在任何Web容器上使用。css
Swashbuckle 是.NET類庫,能夠將WebAPI全部開放的控制器方法生成對應SwaggerUI的JSON配置。再經過SwaggerUI 顯示出來。類庫中已經包含SwaggerUI 。因此不須要額外安裝。html
我儘可能刪除一些咱們demo中不會用到的一些文件,使其看上去比較簡潔。git
WebAPI 安裝 Swashbucklegithub
Install-Package Swashbuckle
代碼註釋生成文檔說明。
Swashbuckle 是經過生成的XML文件來讀取註釋的,生成 SwaggerUI,JSON 配置中的說明的。
安裝時會在項目目錄 App_Start 文件夾下生成一個 SwaggerConfig.cs 配置文件,用於配置 SwaggerUI 相關展現行爲的。如圖:web
c.IncludeXmlComments(GetXmlCommentsPath(thisAssembly.GetName().Name));
並在當前類中添加一個方法json
/// <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 文檔文件」,編譯過程當中生成類庫的註釋文件api
http://<youhost>/swagger/ui/index
,最終顯示效果
在開發移動端 API時經常須要驗證權限,驗證參數放在Http請求頭中是再好不過了。WebAPI配合過濾器驗證權限便可markdown
首先咱們須要建立一個 IOperationFilter 接口的類。IOperationFilterapp
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 配置匿名方法類添加一行註冊代碼dom
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]
最終顯示效果
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 文檔展現效果
你能夠經過下列鏈接獲取相關說明。
Swashbuckle 項目地址:
https://github.com/domaindrivendev/Swashbuckle
swagger-ui 項目地址:
https://github.com/swagger-api/swagger-ui
swagger-ui 官網地址:
http://swagger.io/swagger-ui/