Startup.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.ComponentModel.DataAnnotations;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Http;
  10. using System.Reflection;
  11. using System.Runtime.Remoting.Contexts;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Web.Http;
  15. using System.Web.Http.Description;
  16. using System.Web.Http.Filters;
  17. using System.Web.Http.Metadata;
  18. using System.Web.Http.Routing;
  19. using System.Web.Http.Validation;
  20. using System.Web.Http.Validation.Providers;
  21. using System.Xml;
  22. using System.Xml.Linq;
  23. using Autofac;
  24. using Autofac.Integration.Owin;
  25. using Microsoft.Owin;
  26. using Microsoft.Owin.Cors;
  27. using Newtonsoft.Json;
  28. using Newtonsoft.Json.Serialization;
  29. using Owin;
  30. using Swashbuckle.Application;
  31. using Swashbuckle.Swagger;
  32. using Autofac.Integration.WebApi;
  33. using XdCxRhDw.Dto;
  34. using Autofac.Core;
  35. using Microsoft.Owin.FileSystems;
  36. using Microsoft.Owin.StaticFiles;
  37. [assembly: OwinStartup(typeof(XdCxRhDW.WebApi.Startup))]
  38. namespace XdCxRhDW.WebApi
  39. {
  40. /// <summary>
  41. /// WebApi启动类
  42. /// </summary>
  43. public class Startup
  44. {
  45. /// <summary>
  46. ///
  47. /// </summary>
  48. /// <param name="app"></param>
  49. public void Configuration(IAppBuilder app)
  50. {
  51. app.UseStaticFiles("/wwwroot");
  52. //启用静态目录浏览
  53. //string root = AppDomain.CurrentDomain.BaseDirectory;
  54. //var physicalFileSystem = new PhysicalFileSystem(Path.Combine(root, "wwwroot"));
  55. //var options = new FileServerOptions
  56. //{
  57. // RequestPath = PathString.Empty,
  58. // EnableDefaultFiles = true,
  59. // FileSystem = physicalFileSystem
  60. //};
  61. //options.StaticFileOptions.FileSystem = physicalFileSystem;
  62. //options.StaticFileOptions.ServeUnknownFileTypes = false;
  63. //app.UseFileServer(options);
  64. HttpConfiguration config = new HttpConfiguration();
  65. IEnumerable<ModelValidatorProvider> modelValidatorProviders = config.Services.GetModelValidatorProviders();
  66. DataAnnotationsModelValidatorProvider provider = (DataAnnotationsModelValidatorProvider)
  67. modelValidatorProviders.Single(x => x is DataAnnotationsModelValidatorProvider);
  68. provider.RegisterDefaultValidatableObjectAdapter(typeof(CustomModelValidator));
  69. JsonSerializerSettings setting = new JsonSerializerSettings()
  70. {
  71. //日期类型默认格式化处理
  72. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
  73. DateFormatString = "yyyy-MM-dd HH:mm:ss",
  74. //驼峰样式
  75. //ContractResolver = new CamelCasePropertyNamesContractResolver(),
  76. //空值处理
  77. //NullValueHandling = NullValueHandling.Ignore,
  78. //设置序列化的最大层数
  79. MaxDepth = 10,
  80. //解决json序列化时的循环引用问题
  81. ReferenceLoopHandling = ReferenceLoopHandling.Ignore
  82. };
  83. config.Formatters.JsonFormatter.SerializerSettings = setting;
  84. config.Formatters.Remove(config.Formatters.XmlFormatter);
  85. config.Filters.Add(new HandlerErrorAttribute());
  86. //config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
  87. config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
  88. //config.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
  89. //config.Routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
  90. ConfigureSwagger(config);
  91. //添加路由路径
  92. config.MapHttpAttributeRoutes();
  93. var builder = new ContainerBuilder();
  94. builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
  95. //将程序集中的所有Service注入到容器
  96. var serviceTypes = Assembly.GetExecutingAssembly().GetTypes().Where(p => p.Namespace != null && p.Namespace.EndsWith(".Service")).ToList();
  97. foreach (var serviceType in serviceTypes)
  98. {
  99. //单例模式注入Service
  100. builder.RegisterTypes(serviceType).SingleInstance();
  101. }
  102. var container = builder.Build();
  103. config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
  104. app.UseAutofacLifetimeScopeInjector(container);
  105. app.UseAutofacMiddleware(container);
  106. app.UseAutofacWebApi(config);
  107. app.UseCors(CorsOptions.AllowAll);
  108. app.UseWebApi(config);
  109. }
  110. private static void ConfigureSwagger(HttpConfiguration config)
  111. {
  112. var thisAssembly = typeof(Startup).Assembly;
  113. config.EnableSwagger(c =>
  114. {
  115. c.IgnoreObsoleteActions();//忽略过时的方法
  116. c.IgnoreObsoleteProperties();//忽略过时的属性
  117. c.PrettyPrint();//漂亮缩进
  118. c.SingleApiVersion("v1", "多模式融合定位平台Http接口");
  119. c.ApiKey("123456");
  120. //设置接口描述xml路径地址
  121. var webApiXmlPath1 = $"{AppDomain.CurrentDomain.BaseDirectory}{typeof(Startup).Assembly.GetName().Name}.xml";
  122. c.IncludeXmlComments(webApiXmlPath1);
  123. var webApiXmlPath2 = $"{AppDomain.CurrentDomain.BaseDirectory}{typeof(AjaxResult).Assembly.GetName().Name}.xml";
  124. c.IncludeXmlComments(webApiXmlPath2);
  125. //c.UseFullTypeNameInSchemaIds();//使用完整类型名称
  126. //加入控制器描述
  127. c.CustomProvider((defaultProvider) => new SwaggerControllerDescProvider(defaultProvider, webApiXmlPath1));
  128. c.OperationFilter<FileUploadOperation>();
  129. c.SchemaFilter<SwaggerEnumFilter>();
  130. })
  131. .EnableSwaggerUi(c =>
  132. {
  133. c.InjectJavaScript(thisAssembly, $"{Assembly.GetExecutingAssembly().GetName().Name}.Swagger.js");
  134. c.DocumentTitle("多模式融合定位平台Http接口");
  135. });
  136. }
  137. class FileUploadOperation : IOperationFilter
  138. {
  139. public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
  140. {
  141. if (operation.parameters == null)
  142. {
  143. operation.parameters = new List<Swashbuckle.Swagger.Parameter>();
  144. }
  145. var requestAttributes = apiDescription.GetControllerAndActionAttributes<SwaggerFormAttribute>();
  146. foreach (var attr in requestAttributes)
  147. {
  148. operation.parameters.Add(new Swashbuckle.Swagger.Parameter
  149. {
  150. description = attr.Description,
  151. name = attr.Name,
  152. @in = "formData",
  153. required = true,
  154. type = "file",
  155. });
  156. operation.consumes.Add("multipart/form-data");
  157. }
  158. }
  159. }
  160. class HandlerErrorAttribute : ExceptionFilterAttribute
  161. {
  162. /// <summary>
  163. /// 控制器方法中出现异常,会调用该方法捕获异常
  164. /// </summary>
  165. /// <param name="context">提供使用</param>
  166. public override void OnException(HttpActionExecutedContext context)
  167. {
  168. base.OnException(context);
  169. Serilog.Log.Error(context.Exception, context.Exception.Message);
  170. //LogFile.WriteError(context.Exception.Message);
  171. throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.OK)
  172. {
  173. Content = new StringContent(
  174. JsonConvert.SerializeObject(
  175. new
  176. {
  177. code = -1,
  178. data = "",
  179. msg = context.Exception.Message
  180. }), Encoding.UTF8, "text/json")
  181. });
  182. }
  183. };
  184. class SwaggerControllerDescProvider : ISwaggerProvider
  185. {
  186. private readonly ISwaggerProvider _swaggerProvider;
  187. private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>();
  188. private readonly string _xml;
  189. /// <summary>
  190. ///
  191. /// </summary>
  192. /// <param name="swaggerProvider"></param>
  193. /// <param name="xml">xml文档路径</param>
  194. public SwaggerControllerDescProvider(ISwaggerProvider swaggerProvider, string xml)
  195. {
  196. _swaggerProvider = swaggerProvider;
  197. _xml = xml;
  198. }
  199. public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
  200. {
  201. var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion);
  202. SwaggerDocument srcDoc = null;
  203. //只读取一次
  204. if (!_cache.TryGetValue(cacheKey, out srcDoc))
  205. {
  206. srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion);
  207. srcDoc.vendorExtensions = new Dictionary<string, object> { { "ControllerDesc", GetControllerDesc() } };
  208. _cache.TryAdd(cacheKey, srcDoc);
  209. }
  210. return srcDoc;
  211. }
  212. /// <summary>
  213. /// 从API文档中读取控制器描述
  214. /// </summary>
  215. /// <returns>所有控制器描述</returns>
  216. public ConcurrentDictionary<string, string> GetControllerDesc()
  217. {
  218. string xmlpath = _xml;
  219. ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>();
  220. if (File.Exists(xmlpath))
  221. {
  222. XmlDocument xmldoc = new XmlDocument();
  223. xmldoc.Load(xmlpath);
  224. string type = string.Empty, path = string.Empty, controllerName = string.Empty;
  225. string[] arrPath;
  226. int length = -1, cCount = "Controller".Length;
  227. XmlNode summaryNode = null;
  228. foreach (XmlNode node in xmldoc.SelectNodes("//member"))
  229. {
  230. type = node.Attributes["name"].Value;
  231. if (type.StartsWith("T:"))
  232. {
  233. //控制器
  234. arrPath = type.Split('.');
  235. length = arrPath.Length;
  236. controllerName = arrPath[length - 1];
  237. if (controllerName.EndsWith("Controller"))
  238. {
  239. //获取控制器注释
  240. summaryNode = node.SelectSingleNode("summary");
  241. string key = controllerName.Remove(controllerName.Length - cCount, cCount);
  242. if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key))
  243. {
  244. controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim());
  245. }
  246. }
  247. }
  248. }
  249. }
  250. return controllerDescDict;
  251. }
  252. }
  253. }
  254. /// <summary>
  255. /// Swagger文件上传特性标注
  256. /// </summary>
  257. [AttributeUsage(AttributeTargets.Method)]
  258. public sealed class SwaggerFormAttribute : Attribute
  259. {
  260. /// <summary>
  261. ///
  262. /// </summary>
  263. public SwaggerFormAttribute()
  264. {
  265. this.Name = "文件";
  266. this.Description = "选择文件";
  267. }
  268. /// <summary>
  269. /// Swagger特性标注
  270. /// </summary>
  271. /// <param name="name"></param>
  272. /// <param name="description"></param>
  273. public SwaggerFormAttribute(string name, string description)
  274. {
  275. Name = name;
  276. Description = description;
  277. }
  278. /// <summary>
  279. /// 名称
  280. /// </summary>
  281. public string Name { get; private set; }
  282. /// <summary>
  283. /// 描述
  284. /// </summary>
  285. public string Description { get; private set; }
  286. }
  287. /// <summary>
  288. /// autofac属性注入
  289. /// </summary>
  290. [AttributeUsage(AttributeTargets.Property)]
  291. public class AutowiredAttribute : Attribute
  292. {
  293. }
  294. // 属性注入选择器
  295. class AutowiredPropertySelector : IPropertySelector
  296. {
  297. public bool InjectProperty(PropertyInfo propertyInfo, object instance)
  298. {
  299. // 带有 AutowiredAttribute 特性的属性会进行属性注入
  300. return propertyInfo.CustomAttributes.Any(it => it.AttributeType == typeof(AutowiredAttribute));
  301. }
  302. }
  303. class SwaggerEnumFilter : ISchemaFilter
  304. {
  305. public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
  306. {
  307. UpdateSchemaDescription(schema, type);
  308. }
  309. private void UpdateSchemaDescription(Schema schema, Type type)
  310. {
  311. if (type.IsEnum)//枚举直接应用在controller接口中
  312. {
  313. var items = GetEnumInfo(type);
  314. if (items.Length > 0)
  315. {
  316. var description = GetEnumInfo(type);
  317. schema.description = string.IsNullOrEmpty(schema.description) ? description : $"{schema.description}:{description}";
  318. }
  319. }
  320. else if (type.IsClass && type != typeof(string))//枚举在类的属性中
  321. {
  322. if (schema.properties == null) return;
  323. var props = type.GetProperties();
  324. foreach (var prop in props)
  325. {
  326. var propScheama = schema.properties[prop.Name];
  327. if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string))
  328. {
  329. UpdateSchemaDescription(propScheama, prop.PropertyType);
  330. }
  331. else
  332. {
  333. if (prop.PropertyType.IsEnum)
  334. {
  335. var description = GetEnumInfo(prop.PropertyType);
  336. propScheama.description = string.IsNullOrWhiteSpace(propScheama.description) ? description : $"{propScheama.description}:{description}";
  337. propScheama.@enum = null;
  338. }
  339. }
  340. }
  341. }
  342. }
  343. /// <summary>
  344. /// 获取枚举值+描述
  345. /// </summary>
  346. /// <param name="enumType"></param>
  347. /// <returns></returns>
  348. private string GetEnumInfo(Type enumType)
  349. {
  350. var fields = enumType.GetFields();
  351. List<string> list = new List<string>();
  352. foreach (var field in fields)
  353. {
  354. if (!field.FieldType.IsEnum) continue;
  355. string description = null;
  356. if (description == null)//取DescriptionAttribute的值
  357. {
  358. var descriptionAttr = field.GetCustomAttribute<DescriptionAttribute>();
  359. if (descriptionAttr != null && !string.IsNullOrWhiteSpace(descriptionAttr.Description))
  360. {
  361. description = descriptionAttr.Description;
  362. }
  363. }
  364. if (description == null)//取DisplayAttribute的值
  365. {
  366. var dispalyAttr = field.GetCustomAttribute<DisplayAttribute>();
  367. if (dispalyAttr != null && !string.IsNullOrWhiteSpace(dispalyAttr.Name))
  368. {
  369. description = dispalyAttr.Name;
  370. }
  371. }
  372. if (description == null)//取DisplayNameAttribute的值
  373. {
  374. var dispalyNameAttr = field.GetCustomAttribute<DisplayNameAttribute>();
  375. if (dispalyNameAttr != null && !string.IsNullOrWhiteSpace(dispalyNameAttr.DisplayName))
  376. {
  377. description = dispalyNameAttr.DisplayName;
  378. }
  379. }
  380. if (description == null)//取字段名
  381. {
  382. description = field.Name;
  383. }
  384. var value = field.GetValue(null);
  385. list.Add($"{description}={(int)value}");
  386. }
  387. return string.Join(",", list);
  388. }
  389. }
  390. class CustomModelValidator : ModelValidator
  391. {
  392. public CustomModelValidator(IEnumerable<ModelValidatorProvider> modelValidatorProviders) : base(modelValidatorProviders)
  393. {
  394. }
  395. public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
  396. {
  397. if (metadata.IsComplexType && metadata.Model == null)
  398. {
  399. return new List<ModelValidationResult> { new ModelValidationResult { MemberName = metadata.GetDisplayName(), Message = "请求参数对象不能为空。" } };
  400. }
  401. if (typeof(IValidatableObject).IsAssignableFrom(metadata.ModelType))
  402. {
  403. var validationResult = (metadata.Model as IValidatableObject).Validate(new ValidationContext(metadata.Model));
  404. if (validationResult != null)
  405. {
  406. var modelValidationResults = new List<ModelValidationResult>();
  407. foreach (var result in validationResult)
  408. {
  409. modelValidationResults.Add(new ModelValidationResult
  410. {
  411. MemberName = string.Join(",", result.MemberNames),
  412. Message = result.ErrorMessage
  413. });
  414. }
  415. return modelValidationResults;
  416. }
  417. return null;
  418. }
  419. return GetModelValidator(ValidatorProviders).Validate(metadata, container);
  420. }
  421. }
  422. }