net framework mvc集成swagger
作者:互联网
1.引用swagger
2.引用swagger ui
3.配置输出xml
4.修改SwaggerConfig.cs配置
1 using System.Web.Http; 2 using WebActivatorEx; 3 using DaleCloud.WebApi; 4 using Swashbuckle.Application; 5 using DaleCloud.WebApi.App_Start; 6 using System; 7 using DaleCloud.WebApi.Filters; 8 9 [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] 10 11 namespace DaleCloud.WebApi 12 { 13 public class SwaggerConfig 14 { 15 public static void Register() 16 { 17 var thisAssembly = typeof(SwaggerConfig).Assembly; 18 19 GlobalConfiguration.Configuration 20 .EnableSwagger(c => 21 { 22 23 c.SingleApiVersion("v1", "绵阳涪城智慧监管系统API v1.0"); 24 c.CustomProvider((defaultProvider) => new SwaggerCacheProvider(defaultProvider, string.Format(@"{0}\bin\DaleCloud.WebApi.xml", System.AppDomain.CurrentDomain.BaseDirectory))); 25 c.IncludeXmlComments(GetXmlCommentsPath(GetXmlCommentsPath(thisAssembly.GetName().Name)));//获取接口注释 26 c.OperationFilter<AuthorityHttpHeaderFilter>(); 27 28 29 }) 30 .EnableSwaggerUi(c => 31 { 32 //这里JS资源文件命名空间是:文件所在项目的命名空间.文件径路.文件名 33 c.InjectJavaScript(System.Reflection.Assembly.GetExecutingAssembly(), "DaleCloud.WebApi.swagger-China.js"); 34 }); 35 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\DaleCloud.WebApi.xml", AppDomain.CurrentDomain.BaseDirectory, name); 46 } 47 48 49 50 } 51 }
5.汉化处理
(1)新建js文件swagger-China.js
1 'use strict'; 2 window.SwaggerTranslator = { 3 _words: [], 4 5 translate: function () { 6 var $this = this; 7 $('[data-sw-translate]').each(function () { 8 $(this).html($this._tryTranslate($(this).html())); 9 $(this).val($this._tryTranslate($(this).val())); 10 $(this).attr('title', $this._tryTranslate($(this).attr('title'))); 11 }); 12 }, 13 14 setControllerSummary: function () { 15 16 try { 17 console.log($("#input_baseUrl").val()); 18 $.ajax({ 19 type: "get", 20 async: true, 21 url: $("#input_baseUrl").val(), 22 dataType: "json", 23 success: function (data) { 24 25 var summaryDict = data.ControllerDesc; 26 console.log(summaryDict); 27 var id, controllerName, strSummary; 28 $("#resources_container .resource").each(function (i, item) { 29 id = $(item).attr("id"); 30 if (id) { 31 controllerName = id.substring(9); 32 try { 33 strSummary = summaryDict[controllerName]; 34 if (strSummary) { 35 $(item).children(".heading").children(".options").first().prepend('<li class="controller-summary" style="color:green;" title="' + strSummary + '">' + strSummary + '</li>'); 36 } 37 } catch (e) { 38 console.log(e); 39 } 40 } 41 }); 42 } 43 }); 44 } catch (e) { 45 console.log(e); 46 } 47 }, 48 _tryTranslate: function (word) { 49 return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word; 50 }, 51 52 learn: function (wordsMap) { 53 this._words = wordsMap; 54 } 55 }; 56 57 58 /* jshint quotmark: double */ 59 window.SwaggerTranslator.learn({ 60 "Warning: Deprecated": "警告:已过时", 61 "Implementation Notes": "实现备注", 62 "Response Class": "响应类", 63 "Status": "状态", 64 "Parameters": "参数", 65 "Parameter": "参数", 66 "Value": "值", 67 "Description": "描述", 68 "Parameter Type": "参数类型", 69 "Data Type": "数据类型", 70 "Response Messages": "响应消息", 71 "HTTP Status Code": "HTTP状态码", 72 "Reason": "原因", 73 "Response Model": "响应模型", 74 "Request URL": "请求URL", 75 "Response Body": "响应体", 76 "Response Code": "响应码", 77 "Response Headers": "响应头", 78 "Hide Response": "隐藏响应", 79 "Headers": "头", 80 "Try it out!": "试一下!", 81 "Show/Hide": "显示/隐藏", 82 "List Operations": "显示操作", 83 "Expand Operations": "展开操作", 84 "Raw": "原始", 85 "can't parse JSON. Raw result": "无法解析JSON. 原始结果", 86 "Model Schema": "模型架构", 87 "Model": "模型", 88 "apply": "应用", 89 "Username": "用户名", 90 "Password": "密码", 91 "Terms of service": "服务条款", 92 "Created by": "创建者", 93 "See more at": "查看更多:", 94 "Contact the developer": "联系开发者", 95 "api version": "api版本", 96 "Response Content Type": "响应Content Type", 97 "fetching resource": "正在获取资源", 98 "fetching resource list": "正在获取资源列表", 99 "Explore": "浏览", 100 "Show Swagger Petstore Example Apis": "显示 Swagger Petstore 示例 Apis", 101 "Can't read from server. It may not have the appropriate access-control-origin settings.": "无法从服务器读取。可能没有正确设置access-control-origin。", 102 "Please specify the protocol for": "请指定协议:", 103 "Can't read swagger JSON from": "无法读取swagger JSON于", 104 "Finished Loading Resource Information. Rendering Swagger UI": "已加载资源信息。正在渲染Swagger UI", 105 "Unable to read api": "无法读取api", 106 "from path": "从路径", 107 "server returned": "服务器返回" 108 }); 109 $(function () { 110 window.SwaggerTranslator.translate(); 111 window.SwaggerTranslator.setControllerSummary(); 112 });
(2)将该JS文件设置为嵌入式资源
(3).修改swagger.config
6.让swagger显示控制器注释
新建类SwaggerCacheProvider.cs
1 using Swashbuckle.Swagger; 2 using System; 3 using System.Collections.Concurrent; 4 using System.Collections.Generic; 5 using System.IO; 6 using System.Linq; 7 using System.Web; 8 using System.Xml; 9 10 namespace DaleCloud.WebApi.App_Start 11 { 12 /// <summary> 13 /// swagger显示控制器的描述 14 /// </summary> 15 public class SwaggerCacheProvider : ISwaggerProvider 16 { 17 private readonly ISwaggerProvider _swaggerProvider; 18 private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>(); 19 private readonly string _xml; 20 /// <summary> 21 /// 22 /// </summary> 23 /// <param name="swaggerProvider"></param> 24 /// <param name="xml">xml文档路径</param> 25 public SwaggerCacheProvider(ISwaggerProvider swaggerProvider, string xml) 26 { 27 _swaggerProvider = swaggerProvider; 28 _xml = xml; 29 } 30 31 public SwaggerDocument GetSwagger(string rootUrl, string apiVersion) 32 { 33 34 var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion); 35 SwaggerDocument srcDoc = null; 36 //只读取一次 37 if (!_cache.TryGetValue(cacheKey, out srcDoc)) 38 { 39 srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion); 40 41 srcDoc.vendorExtensions = new Dictionary<string, object> { { "ControllerDesc", GetControllerDesc() } }; 42 _cache.TryAdd(cacheKey, srcDoc); 43 } 44 return srcDoc; 45 } 46 47 /// <summary> 48 /// 从API文档中读取控制器描述 49 /// </summary> 50 /// <returns>所有控制器描述</returns> 51 public ConcurrentDictionary<string, string> GetControllerDesc() 52 { 53 string xmlpath = _xml; 54 ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>(); 55 if (File.Exists(xmlpath)) 56 { 57 XmlDocument xmldoc = new XmlDocument(); 58 xmldoc.Load(xmlpath); 59 string type = string.Empty, path = string.Empty, controllerName = string.Empty; 60 61 string[] arrPath; 62 int length = -1, cCount = "Controller".Length; 63 XmlNode summaryNode = null; 64 foreach (XmlNode node in xmldoc.SelectNodes("//member")) 65 { 66 type = node.Attributes["name"].Value; 67 if (type.StartsWith("T:")) 68 { 69 //控制器 70 arrPath = type.Split('.'); 71 length = arrPath.Length; 72 controllerName = arrPath[length - 1]; 73 if (controllerName.EndsWith("Controller")) 74 { 75 //获取控制器注释 76 summaryNode = node.SelectSingleNode("summary"); 77 string key = controllerName.Remove(controllerName.Length - cCount, cCount); 78 if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key)) 79 { 80 controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim()); 81 } 82 } 83 } 84 } 85 } 86 return controllerDescDict; 87 } 88 } 89 90 }
配置swagger.config配置文件
7..接口需要在请求头(Request Headers)加身份验证。
新建类:AuthorityHttpHeaderFilter.cs
1 using Swashbuckle.Swagger; 2 using System; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Web; 6 using System.Web.Http.Description; 7 8 namespace DaleCloud.WebApi.Filters 9 { 10 public class AuthorityHttpHeaderFilter : IOperationFilter 11 { 12 public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) 13 { 14 if (operation.parameters == null) 15 operation.parameters = new List<Parameter>(); 16 17 //判断是否添加权限过滤器 18 19 var isAuthorized = apiDescription.ActionDescriptor.GetCustomAttributes<ApiAuthorizeAttribute>().Any(); 20 if (isAuthorized) 21 { 22 operation.parameters.Add(new Parameter { name = "token", @in = "header", description = "令牌", required = false, type = "string" }); 23 } 24 } 25 26 27 } 28 }
修改SwaggerConfig.cs
标签:WebApi,string,System,framework,mvc,using,net,swagger,DaleCloud 来源: https://www.cnblogs.com/cdzhengrui/p/16468724.html