using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Xml; using System.Linq; using System.Web.Http; using WebActivatorEx; using Swashbuckle.Application; using Swashbuckle.Swagger; using GSYWApi; [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] namespace GSYWApi { /// /// /// public class SwaggerConfig { /// /// 注册事件 /// public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "GSYWApi"); c.IncludeXmlComments(string.Format("{0}/bin/GSYWApi.XML", System.AppDomain.CurrentDomain.BaseDirectory));//设置xml地址 c.CustomProvider((defaultProvider) => new CachingSwaggerProvider(defaultProvider)); c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); }) .EnableSwaggerUi(c => { c.DocumentTitle("My webapi"); c.InjectJavaScript(thisAssembly, "GSYWApi.Scripts.Swagger.swagger_lang.js");//汉化js }); } } /// /// /// public class CachingSwaggerProvider : ISwaggerProvider { private static ConcurrentDictionary _cache = new ConcurrentDictionary(); 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 { { "ControllerDesc", GetControllerDesc() } }; _cache.TryAdd(cacheKey, srcDoc); } return srcDoc; } /// /// 从API文档中读取控制器描述 /// /// 所有控制器描述 public static ConcurrentDictionary GetControllerDesc() { string xmlpath = string.Format("{0}/bin/YFBusinessApi.XML", System.AppDomain.CurrentDomain.BaseDirectory); ConcurrentDictionary controllerDescDict = new ConcurrentDictionary(); 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; } } }