一、前言
相信很多小伙伴对 WebApiTestClient 很熟悉,今天讲的是公司目前想更换一个生成接口文档的插件工具就让我去了解 Swagger-ui 生成文档接口,为什么公司用的好好的想换一个而不影响原有的生成接口文档插件工具呢,原因就是接口多了加载接口文档超慢的!
Swagger-ui 生成文档接口目前用的是 .Net Framework ,用了之后我觉得这个东西比 WebApiTestClient 还要慢可以说是加载不出来!听说 .Net Core 版本是可以分组的但是看了一下分组需要准备的东西就觉得目前公司也不是很适用,但是既然学习了如何搭建和使用做个笔录也不错!
二、使用nuget加入Swashbuckle的引用
无需任何修改可直访问http://localhost:52975/swagger/ui/index
三、SwaggerConfig简单介绍
SwaggerConfig.cs文件会自动添加到项目的App_Start目录下,代码本身包含大量注释掉的代码,清除后,代码如下:
using System.Web.Http; using WebActivatorEx; using Swagger.Admin.Api; using Swashbuckle.Application; [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] namespace Swagger.Admin.Api { public class SwaggerConfig { public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "Swagger.Admin.Api"); }) .EnableSwaggerUi(c => { }); } } }
相关工程需要生成XML文档
在 SwaggerConfig.cs 下添加 GetXmlCommentsPath() 方法获取多个工程文档路径(在这里就不做单个演示了基本都差不多):
/// <summary> /// 工程生成的xml文档 /// </summary> /// <returns></returns> private static string[] GetXmlCommentsPath() {
//*是匹配的意思 return Directory.GetFiles($"{System.AppDomain.CurrentDomain.BaseDirectory}/bin/", "swagger.*.xml"); }
在 SwaggerConfig.cs 的 Register 方法的 EnableSwagger 匿名函数中加上对应的XML文件,修改如下:
using System.Web.Http; using WebActivatorEx; using Swagger.Admin.Api; using Swashbuckle.Application; using System.IO; [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] namespace Swagger.Admin.Api { public class SwaggerConfig { /// <summary> /// 工程生成的xml文档 /// </summary> /// <returns></returns> private static string[] GetXmlCommentsPath() { return Directory.GetFiles($"{System.AppDomain.CurrentDomain.BaseDirectory}/bin/", "swagger.*.xml"); } /// <summary> /// 寄存器 /// </summary> public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "Swagger.Admin.Api"); foreach (var item in GetXmlCommentsPath()) { c.IncludeXmlComments(item); } }) .EnableSwaggerUi(c => { }); } } }
添加一个swagger.Order工程类库添加OrderController.cs控制器
using System.Web.Http; namespace swagger.Order { /// <summary> /// 订单 /// </summary> public class OrderController : ApiController { /// <summary> /// 订单首页 /// </summary> /// <returns></returns> [Route("Index")] public string Index() { return "order"; } } }
右键设置swagger.Order工程类库
把 Swagger.Admin.Api 工程下的 ValuesController.cs 控制器修改如下
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace Swagger.Admin.Api.Controllers { /// <summary> /// 默认测试控制器 /// </summary> public class ValuesController : ApiController { /// <summary> /// Get方法 /// </summary> /// <returns></returns> public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } /// <summary> /// 带参数Get方法 /// </summary> /// <param name="id"></param> /// <returns></returns> public string Get(int id) { return "value"; } /// <summary> /// Post方法 /// </summary> /// <param name="value"></param> public void Post([FromBody]string value) { } /// <summary> /// Put方法 /// </summary> /// <param name="id"></param> /// <param name="value"></param> public void Put(int id, [FromBody]string value) { } /// <summary> /// Delete方法 /// </summary> /// <param name="id"></param> public void Delete(int id) { } } }
修改好了记得生成一下 swagger.Order 工程项目,然后运行看下是否有文档描述
为什么控制器的注释没有列出来还有我想要汉化版本的怎么处理呢,别急现在就上代码!
1.在Scripts 下添加 Swagger.js 文件
'use strict'; window.SwaggerTranslator = { _words: [], translate: function () { var $this = this; $('[data-sw-translate]').each(function () { $(this).html($this._tryTranslate($(this).html())); $(this).val($this._tryTranslate($(this).val())); $(this).attr('title', $this._tryTranslate($(this).attr('title'))); }); }, setControllerSummary: function () { try { console.log($("#input_baseUrl").val()); $.ajax({ type: "get", async: true, url: $("#input_baseUrl").val(), dataType: "json", success: function (data) { var summaryDict = data.ControllerDesc; console.log(summaryDict); var id, controllerName, strSummary; $("#resources_container .resource").each(function (i, item) { id = $(item).attr("id"); if (id) { controllerName = id.substring(9); try { strSummary = summaryDict[controllerName]; if (strSummary) { $(item).children(".heading").children(".options").first().prepend('<li class="controller-summary" style="color:green;" title="' + strSummary + '">' + strSummary + '</li>'); } } catch (e) { console.log(e); } } }); } }); } catch (e) { console.log(e); } }, _tryTranslate: function (word) { return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word; }, learn: function (wordsMap) { this._words = wordsMap; } }; /* jshint quotmark: double */ window.SwaggerTranslator.learn({ "Warning: Deprecated": "警告:已过时", "Implementation Notes": "实现备注", "Response Class": "响应类", "Status": "状态", "Parameters": "参数", "Parameter": "参数", "Value": "值", "Description": "描述", "Parameter Type": "参数类型", "Data Type": "数据类型", "Response Messages": "响应消息", "HTTP Status Code": "HTTP状态码", "Reason": "原因", "Response Model": "响应模型", "Request URL": "请求URL", "Response Body": "响应体", "Response Code": "响应码", "Response Headers": "响应头", "Hide Response": "隐藏响应", "Headers": "头", "Try it out!": "试一下!", "Show/Hide": "显示/隐藏", "List Operations": "显示操作", "Expand Operations": "展开操作", "Raw": "原始", "can't parse JSON. Raw result": "无法解析JSON. 原始结果", "Model Schema": "模型架构", "Model": "模型", "apply": "应用", "Username": "用户名", "Password": "密码", "Terms of service": "服务条款", "Created by": "创建者", "See more at": "查看更多:", "Contact the developer": "联系开发者", "api version": "api版本", "Response Content Type": "响应Content Type", "fetching resource": "正在获取资源", "fetching resource list": "正在获取资源列表", "Explore": "浏览", "Show Swagger Petstore Example Apis": "显示 Swagger Petstore 示例 Apis", "Can't read from server. It may not have the appropriate access-control-origin settings.": "无法从服务器读取。可能没有正确设置access-control-origin。", "Please specify the protocol for": "请指定协议:", "Can't read swagger JSON from": "无法读取swagger JSON于", "Finished Loading Resource Information. Rendering Swagger UI": "已加载资源信息。正在渲染Swagger UI", "Unable to read api": "无法读取api", "from path": "从路径", "server returned": "服务器返回" }); $(function () { window.SwaggerTranslator.translate(); window.SwaggerTranslator.setControllerSummary(); });
生成操作改为
2.在App_Start文件夹下添加 SwaggerCacheProvider.cs
using Swashbuckle.Swagger; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Xml; namespace Swagger.Admin.Api { public class SwaggerCacheProvider : ISwaggerProvider { private readonly ISwaggerProvider _swaggerProvider; private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>(); private readonly string[] _xmls; /// <summary> /// /// </summary> /// <param name="swaggerProvider"></param> /// <param name="xmls"></param> /// <param name="xml">xml文档路径</param> public SwaggerCacheProvider(ISwaggerProvider swaggerProvider, params string[] xmls) { _swaggerProvider = swaggerProvider; _xmls = xmls; } 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 ConcurrentDictionary<string, string> GetControllerDesc() { string[] xmlpaths = _xmls; ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>(); foreach (var xmlpath in xmlpaths) { 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; } } }
修改 SwaggerConfig.cs 的 Register 方法(我直接把整个cs贴过来算了)
using System.Web.Http; using WebActivatorEx; using Swagger.Admin.Api; using Swashbuckle.Application; using System.IO; [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] namespace Swagger.Admin.Api { public class SwaggerConfig { /// <summary> /// 工程生成的xml文档 /// </summary> /// <returns></returns> private static string[] GetXmlCommentsPath() { return Directory.GetFiles($"{System.AppDomain.CurrentDomain.BaseDirectory}/bin/", "swagger.*.xml"); } /// <summary> /// 寄存器 /// </summary> public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "Swagger.Admin.Api"); //处理控制器注释 c.CustomProvider((defaultProvider) => new SwaggerCacheProvider(defaultProvider, GetXmlCommentsPath())); foreach (var item in GetXmlCommentsPath()) { c.IncludeXmlComments(item); } }) .EnableSwaggerUi(c => { c.InjectJavaScript(System.Reflection.Assembly.GetExecutingAssembly(), "Swagger.Admin.Api.Scripts.Swagger.js"); }); } } }
然后运行一下试试效果
大功告成,简单的Swagger-ui 的搭建与使用就讲到这里了!
当接口多的时候超慢,要加分组功能目前好像是 Swagger2 (.net core)才有整个操作或者是我没有仔细研究,有办法解决慢的小伙伴留言交流一下!