WebApi自动接口文档Swagger汉化和添加Token验证
最近做的项目使用mvc+webapi,采取前后端分离的方式,后台提供API接口给前端开发人员。
这个过程中遇到一个问题后台开发人员怎么提供接口说明文档给前端开发人员。
为了解决这个问题,项目中引用swagger(我比较喜欢戏称为“丝袜哥”)
这篇文章介绍的Swagger的使用比较详细 https://www.cnblogs.com/yanweidie/p/5709113.html
实现效果
1.列出所有API控制器和控制器描述
2.列出action和描述
3.直观的接口测试
1.WebApi项目中引入Swagger nuget添加下图两个包
2.配置Swagger和配置项目输出XML文档,用于显示注释
3.汉化问题Swagger汉化
SwaggerConfig.cs修改源码如下
1 using System.Web.Http; 2 using WebActivatorEx; 3 using FamilyDoctorWebApi; 4 using Swashbuckle.Application; 5 using System; 6 using System.Collections.Concurrent; 7 using Swashbuckle.Swagger; 8 using System.Collections.Generic; 9 using System.Xml; 10 using System.IO; 11 12 [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] 13 namespace FamilyDoctorWebApi 14 { 15 /// <summary> 16 /// 17 /// </summary> 18 public class SwaggerConfig 19 { 20 public static void Register() 21 { 22 var thisAssembly = typeof(SwaggerConfig).Assembly; 23 24 GlobalConfiguration.Configuration 25 .EnableSwagger(c => 26 { 27 c.SingleApiVersion("v1", "家庭医生WebApi接口文档"); 28 c.IncludeXmlComments(GetXmlCommentsPath(thisAssembly.GetName().Name)); 29 c.UseFullTypeNameInSchemaIds(); 30 c.CustomProvider((defaultProvider) => new CachingSwaggerProvider(defaultProvider)); 31 }) 32 .EnableSwaggerUi(c => 33 { 34 //路径规则,项目命名空间.文件夹名称.js文件名称 35 c.InjectJavaScript(thisAssembly, "FamilyDoctorWebApi.Scripts.swagger.js"); 36 }); 37 } 38 /// <summary> 39 /// 40 /// </summary> 41 /// <param name="name"></param> 42 /// <returns></returns> 43 protected static string GetXmlCommentsPath(string name) 44 { 45 return string.Format(@"{0}\bin\{1}.XML", AppDomain.CurrentDomain.BaseDirectory, name); 46 } 47 } 48 49 public class CachingSwaggerProvider : Swashbuckle.Swagger.ISwaggerProvider 50 { 51 private static ConcurrentDictionary<string, SwaggerDocument> _cache = 52 new ConcurrentDictionary<string, SwaggerDocument>(); 53 54 private readonly ISwaggerProvider _swaggerProvider; 55 56 public CachingSwaggerProvider(ISwaggerProvider swaggerProvider) 57 { 58 _swaggerProvider = swaggerProvider; 59 } 60 61 public SwaggerDocument GetSwagger(string rootUrl, string apiVersion) 62 { 63 var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion); 64 SwaggerDocument srcDoc = null; 65 //只读取一次 66 if (!_cache.TryGetValue(cacheKey, out srcDoc)) 67 { 68 srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion); 69 70 srcDoc.vendorExtensions = new Dictionary<string, object> { { "ControllerDesc", GetControllerDesc() } }; 71 _cache.TryAdd(cacheKey, srcDoc); 72 } 73 return srcDoc; 74 } 75 76 /// <summary> 77 /// 从API文档中读取控制器描述 78 /// </summary> 79 /// <returns>所有控制器描述</returns> 80 public static ConcurrentDictionary<string, string> GetControllerDesc() 81 { 82 string xmlpath = string.Format("{0}/bin/{1}.XML", System.AppDomain.CurrentDomain.BaseDirectory, typeof(SwaggerConfig).Assembly.GetName().Name); 83 ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>(); 84 if (File.Exists(xmlpath)) 85 { 86 XmlDocument xmldoc = new XmlDocument(); 87 xmldoc.Load(xmlpath); 88 string type = string.Empty, path = string.Empty, controllerName = string.Empty; 89 90 string[] arrPath; 91 int length = -1, cCount = "Controller".Length; 92 XmlNode summaryNode = null; 93 foreach (XmlNode node in xmldoc.SelectNodes("//member")) 94 { 95 type = node.Attributes["name"].Value; 96 if (type.StartsWith("T:")) 97 { 98 //控制器 99 arrPath = type.Split('.'); 100 length = arrPath.Length; 101 controllerName = arrPath[length - 1]; 102 if (controllerName.EndsWith("Controller")) 103 { 104 //获取控制器注释 105 summaryNode = node.SelectSingleNode("summary"); 106 string key = controllerName.Remove(controllerName.Length - cCount, cCount); 107 if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key)) 108 { 109 controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim()); 110 } 111 } 112 } 113 } 114 } 115 return controllerDescDict; 116 } 117 } 118 }
c.InjectJavaScript(thisAssembly, "FamilyDoctorWebApi.Scripts.swagger.js");//这行代码需要配置
汉化JS包如下(swagger.js是嵌入的资源)
1 var SwaggerTranslator = (function () { 2 //定时执行检测是否转换成中文,最多执行500次 即500*50/1000=25s 3 var iexcute = 0, 4 //中文语言包 5 _words = { 6 "Warning: Deprecated": "警告:已过时", 7 "Implementation Notes": "实现备注", 8 "Response Class": "响应类", 9 "Status": "状态", 10 "Parameters": "参数", 11 "Parameter": "参数", 12 "Value": "值", 13 "Description": "描述", 14 "Parameter Type": "参数类型", 15 "Data Type": "数据类型", 16 "Response Messages": "响应消息", 17 "HTTP Status Code": "HTTP状态码", 18 "Reason": "原因", 19 "Response Model": "响应模型", 20 "Request URL": "请求URL", 21 "Response Body": "响应体", 22 "Response Code": "响应码", 23 "Response Headers": "响应头", 24 "Hide Response": "隐藏响应", 25 "Headers": "头", 26 "Try it out!": "试一下!", 27 "Example Value": "示例值", 28 "Show/Hide": "显示/隐藏", 29 "List Operations": "显示操作", 30 "Expand Operations": "展开操作", 31 "Raw": "原始", 32 "can't parse JSON. Raw result": "无法解析JSON. 原始结果", 33 "Model Schema": "模型架构", 34 "Model": "模型", 35 "apply": "应用", 36 "Username": "用户名", 37 "Password": "密码", 38 "Terms of service": "服务条款", 39 "Created by": "创建者", 40 "See more at": "查看更多:", 41 "Contact the developer": "联系开发者", 42 "api version": "api版本", 43 "Response Content Type": "响应Content Type", 44 "fetching resource": "正在获取资源", 45 "fetching resource list": "正在获取资源列表", 46 "Explore": "浏览", 47 "Show Swagger Petstore Example Apis": "显示 Swagger Petstore 示例 Apis", 48 "Can't read from server. It may not have the appropriate access-control-origin settings.": "无法从服务器读取。可能没有正确设置access-control-origin。", 49 "Please specify the protocol for": "请指定协议:", 50 "Can't read swagger JSON from": "无法读取swagger JSON于", 51 "Finished Loading Resource Information. Rendering Swagger UI": "已加载资源信息。正在渲染Swagger UI", 52 "Unable to read api": "无法读取api", 53 "from path": "从路径", 54 "Click to set as parameter value": "点击设置参数", 55 "server returned": "服务器返回" 56 }, 57 //定时执行转换 58 _translator2Cn = function () { 59 if ($("#resources_container .resource").length > 0) { 60 _tryTranslate(); 61 } 62 63 if ($("#explore").text() == "Explore" && iexcute < 500) { 64 iexcute++; 65 setTimeout(_translator2Cn, 50); 66 } 67 }, 68 69 //设置控制器注释 70 _setControllerSummary = function () { 71 $.ajax({ 72 type: "get", 73 async: true, 74 url: $("#input_baseUrl").val(), 75 dataType: "json", 76 success: function (data) { 77 var summaryDict = data.ControllerDesc; 78 var id, controllerName, strSummary; 79 $("#resources_container .resource").each(function (i, item) { 80 id = $(item).attr("id"); 81 if (id) { 82 controllerName = id.substring(9); 83 strSummary = summaryDict[controllerName]; 84 if (strSummary) { 85 $(item).children(".heading").children(".options").prepend('<li class="controller-summary" title="' + strSummary + '">' + strSummary + '</li>'); 86 } 87 } 88 }); 89 } 90 }); 91 }, 92 93 //尝试将英文转换成中文 94 _tryTranslate = function () { 95 $('[data-sw-translate]').each(function () { 96 $(this).html(_getLangDesc($(this).html())); 97 $(this).val(_getLangDesc($(this).val())); 98 $(this).attr('title', _getLangDesc($(this).attr('title'))); 99 }); 100 }, 101 _getLangDesc = function (word) { 102 return _words[$.trim(word)] !== undefined ? _words[$.trim(word)] : word; 103 }; 104 105 return { 106 Translator: function () { 107 document.title = "API描述文档"; 108 $('body').append('<style type="text/css">.controller-summary{color:#10a54a !important;word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:250px;text-align:right;cursor:default;} </style>'); 109 $("#logo").html("接口描述").attr("href", "/Home/Index"); 110 //设置控制器描述 111 _setControllerSummary(); 112 _translator2Cn(); 113 } 114 } 115 })(); 116 //执行转换 117 SwaggerTranslator.Translator();
注:swagger发布环境显示error。在swagger.js添加一行代码隐藏警告提示:$("#validator").parent().hide();
添加Token验证
共两步:
第一步:添加过滤器
public class GlobalHttpHeaderFilter : IOperationFilter { public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { if (operation.parameters == null) operation.parameters = new List<Parameter>(); operation.parameters.Add(new Parameter { name = "staffid", @in = "header", description = "用户手机号", required = false, type = "string" }); operation.parameters.Add(new Parameter { name = "timestamp", @in = "header", description = "时间戳", required = false, type = "string" }); operation.parameters.Add(new Parameter { name = "signtoken", @in = "header", description = "Token", required = false, type = "string" }); } }
第二步:修改Swagger的路由配置
using System.Web.Http; using WebActivatorEx; using FamilyDoctorWebApi; using Swashbuckle.Application; using System; using System.Collections.Concurrent; using Swashbuckle.Swagger; using System.Collections.Generic; using System.Xml; using System.IO; [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] namespace FamilyDoctorWebApi { /// <summary> /// /// </summary> public class SwaggerConfig { public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "家庭医生WebApi接口文档"); c.IncludeXmlComments(GetXmlCommentsPath(thisAssembly.GetName().Name)); c.UseFullTypeNameInSchemaIds(); c.CustomProvider((defaultProvider) => new CachingSwaggerProvider(defaultProvider));//汉化Swagger两步:第一步 c.OperationFilter<FamilyDoctorWebApi.Filter.GlobalHttpHeaderFilter>();//添加过滤器,增加Token令牌验证 }) .EnableSwaggerUi(c => { c.InjectJavaScript(thisAssembly, "FamilyDoctorWebApi.Scripts.swagger.js");//汉化Swagger两步:第二步 }); } /// <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); } } public class CachingSwaggerProvider : Swashbuckle.Swagger.ISwaggerProvider { private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>(); private readonly ISwaggerProvider _swaggerProvider; public CachingSwaggerProvider(ISwaggerProvider swaggerProvider) { _swaggerProvider = swaggerProvider; } public SwaggerDocument GetSwagger(string rootUrl, string apiVersion) { var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion); SwaggerDocument srcDoc = null; //只读取一次 if (!_cache.TryGetValue(cacheKey, out srcDoc)) { srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion); srcDoc.vendorExtensions = new Dictionary<string, object> { { "ControllerDesc", GetControllerDesc() } }; _cache.TryAdd(cacheKey, srcDoc); } return srcDoc; } /// <summary> /// 从API文档中读取控制器描述 /// </summary> /// <returns>所有控制器描述</returns> public static ConcurrentDictionary<string, string> GetControllerDesc() { string xmlpath = string.Format("{0}/bin/{1}.XML", System.AppDomain.CurrentDomain.BaseDirectory, typeof(SwaggerConfig).Assembly.GetName().Name); ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>(); if (File.Exists(xmlpath)) { XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(xmlpath); string type = string.Empty, path = string.Empty, controllerName = string.Empty; string[] arrPath; int length = -1, cCount = "Controller".Length; XmlNode summaryNode = null; foreach (XmlNode node in xmldoc.SelectNodes("//member")) { type = node.Attributes["name"].Value; if (type.StartsWith("T:")) { //控制器 arrPath = type.Split('.'); length = arrPath.Length; controllerName = arrPath[length - 1]; if (controllerName.EndsWith("Controller")) { //获取控制器注释 summaryNode = node.SelectSingleNode("summary"); string key = controllerName.Remove(controllerName.Length - cCount, cCount); if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key)) { controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim()); } } } } } return controllerDescDict; } } }
搞定
一个自由.NET开发者
bingqiang1903@gmail.com
https://www.cnblogs.com/sunbingqiang/