Startup.cs 18 KB

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