using Swashbuckle.Swagger; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Web.Http.Description; using System.Xml; namespace UFIDA.U8.Framework.Api { /// public class SwaggerCacheProvider : ISwaggerProvider { private readonly ISwaggerProvider _swaggerProvider; private static readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); private readonly string _xmlPath; /// /// /// /// /// xml文档路径 public SwaggerCacheProvider(ISwaggerProvider swaggerProvider, string xmlpath) { _swaggerProvider = swaggerProvider; _xmlPath = xmlpath; } /// public SwaggerDocument GetSwagger(string rootUrl, string apiVersion) { var cacheKey = $"{rootUrl}_{apiVersion}"; //只读取一次 if (!_cache.TryGetValue(cacheKey, out var srcDoc)) { srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion); srcDoc.vendorExtensions = new Dictionary { { "ControllerDesc", GetControllerDesc() } }; _cache.TryAdd(cacheKey, srcDoc); } return srcDoc; } /// /// 从API文档中读取控制器描述 /// /// 所有控制器描述 public ConcurrentDictionary GetControllerDesc() { var controllerDescDict = new ConcurrentDictionary(); if (File.Exists(_xmlPath)) { var xmldoc = new XmlDocument(); xmldoc.Load(_xmlPath); var cCount = "Controller".Length; var nodes = xmldoc.SelectNodes("//member"); if (nodes == null || nodes.Count <= 0) return null; foreach (XmlNode node in nodes) { var type = node.Attributes?["name"].Value; if (type != null && !type.StartsWith("T:")) continue; var arrPath = type?.Split('.'); var controllerName = arrPath?[arrPath.Length - 1]; if (controllerName != null && controllerName.EndsWith("Controller")) //控制器 { //获取控制器注释 var summaryNode = node.SelectSingleNode("summary"); var 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; } } /// public class TokenRequiredHeaderParameter : IOperationFilter { /// /// 参数名称 /// public static string HeaderKey { get; set; } /// /// 参数说明 /// public static string Description { get; set; } /// public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { if (operation.parameters == null) operation.parameters = new List(); operation.parameters.Add(new Parameter { name = HeaderKey, required = false, description = Description, type = "string", @in = "header" }); } } }