Startup.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. using System.Threading.Tasks;
  38. [assembly: OwinStartup(typeof(XdCxRhDW.WebApi.Startup))]
  39. namespace XdCxRhDW.WebApi
  40. {
  41. /// <summary>
  42. /// WebApi启动类
  43. /// </summary>
  44. public class Startup
  45. {
  46. /// <summary>
  47. ///
  48. /// </summary>
  49. /// <param name="app"></param>
  50. public void Configuration(IAppBuilder app)
  51. {
  52. //启用目录浏览和静态文件
  53. var physicalFileSystem = new PhysicalFileSystem(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot"));//目录浏览物理地址
  54. var options = new FileServerOptions
  55. {
  56. RequestPath = new PathString("/wwwroot"),//目录浏览地址
  57. EnableDefaultFiles = true,
  58. EnableDirectoryBrowsing = true,//启用目录浏览
  59. FileSystem = physicalFileSystem
  60. };
  61. options.StaticFileOptions.FileSystem = physicalFileSystem;
  62. options.StaticFileOptions.ServeUnknownFileTypes = true;//允许下载wwwroot中的所有类型文件
  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. string msg = context.Exception.Message;
  172. if (context.Exception.GetType() == typeof(FileNotFoundException))
  173. {
  174. //防止程序路径泄露到前端
  175. msg = "未能找到文件" + context.Exception.Message.Substring(context.Exception.Message.LastIndexOf("\\") + 1);
  176. }
  177. throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.OK)
  178. {
  179. Content = new StringContent(
  180. JsonConvert.SerializeObject(
  181. new AjaxResult
  182. {
  183. code = 0,
  184. data = null,
  185. msg = msg
  186. }), Encoding.UTF8, "text/json")
  187. });
  188. }
  189. };
  190. class SwaggerControllerDescProvider : ISwaggerProvider
  191. {
  192. private readonly ISwaggerProvider _swaggerProvider;
  193. private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>();
  194. private readonly string _xml;
  195. /// <summary>
  196. ///
  197. /// </summary>
  198. /// <param name="swaggerProvider"></param>
  199. /// <param name="xml">xml文档路径</param>
  200. public SwaggerControllerDescProvider(ISwaggerProvider swaggerProvider, string xml)
  201. {
  202. _swaggerProvider = swaggerProvider;
  203. _xml = xml;
  204. }
  205. public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
  206. {
  207. var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion);
  208. SwaggerDocument srcDoc = null;
  209. //只读取一次
  210. if (!_cache.TryGetValue(cacheKey, out srcDoc))
  211. {
  212. srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion);
  213. srcDoc.vendorExtensions = new Dictionary<string, object> { { "ControllerDesc", GetControllerDesc() } };
  214. _cache.TryAdd(cacheKey, srcDoc);
  215. }
  216. return srcDoc;
  217. }
  218. /// <summary>
  219. /// 从API文档中读取控制器描述
  220. /// </summary>
  221. /// <returns>所有控制器描述</returns>
  222. public ConcurrentDictionary<string, string> GetControllerDesc()
  223. {
  224. string xmlpath = _xml;
  225. ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>();
  226. if (File.Exists(xmlpath))
  227. {
  228. XmlDocument xmldoc = new XmlDocument();
  229. xmldoc.Load(xmlpath);
  230. string type = string.Empty, path = string.Empty, controllerName = string.Empty;
  231. string[] arrPath;
  232. int length = -1, cCount = "Controller".Length;
  233. XmlNode summaryNode = null;
  234. foreach (XmlNode node in xmldoc.SelectNodes("//member"))
  235. {
  236. type = node.Attributes["name"].Value;
  237. if (type.StartsWith("T:"))
  238. {
  239. //控制器
  240. arrPath = type.Split('.');
  241. length = arrPath.Length;
  242. controllerName = arrPath[length - 1];
  243. if (controllerName.EndsWith("Controller"))
  244. {
  245. //获取控制器注释
  246. summaryNode = node.SelectSingleNode("summary");
  247. string key = controllerName.Remove(controllerName.Length - cCount, cCount);
  248. if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key))
  249. {
  250. controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim());
  251. }
  252. }
  253. }
  254. }
  255. }
  256. return controllerDescDict;
  257. }
  258. }
  259. }
  260. /// <summary>
  261. /// Swagger文件上传特性标注
  262. /// </summary>
  263. [AttributeUsage(AttributeTargets.Method)]
  264. public sealed class SwaggerFormAttribute : Attribute
  265. {
  266. /// <summary>
  267. ///
  268. /// </summary>
  269. public SwaggerFormAttribute()
  270. {
  271. this.Name = "文件";
  272. this.Description = "选择文件";
  273. }
  274. /// <summary>
  275. /// Swagger特性标注
  276. /// </summary>
  277. /// <param name="name"></param>
  278. /// <param name="description"></param>
  279. public SwaggerFormAttribute(string name, string description)
  280. {
  281. Name = name;
  282. Description = description;
  283. }
  284. /// <summary>
  285. /// 名称
  286. /// </summary>
  287. public string Name { get; private set; }
  288. /// <summary>
  289. /// 描述
  290. /// </summary>
  291. public string Description { get; private set; }
  292. }
  293. /// <summary>
  294. /// autofac属性注入
  295. /// </summary>
  296. [AttributeUsage(AttributeTargets.Property)]
  297. public class AutowiredAttribute : Attribute
  298. {
  299. }
  300. // 属性注入选择器
  301. class AutowiredPropertySelector : IPropertySelector
  302. {
  303. public bool InjectProperty(PropertyInfo propertyInfo, object instance)
  304. {
  305. // 带有 AutowiredAttribute 特性的属性会进行属性注入
  306. return propertyInfo.CustomAttributes.Any(it => it.AttributeType == typeof(AutowiredAttribute));
  307. }
  308. }
  309. class SwaggerEnumFilter : ISchemaFilter
  310. {
  311. public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
  312. {
  313. UpdateSchemaDescription(schema, type);
  314. }
  315. private void UpdateSchemaDescription(Schema schema, Type type)
  316. {
  317. if (type.IsEnum)//枚举直接应用在controller接口中
  318. {
  319. var items = GetEnumInfo(type);
  320. if (items.Length > 0)
  321. {
  322. var description = GetEnumInfo(type);
  323. schema.description = string.IsNullOrEmpty(schema.description) ? description : $"{schema.description}:{description}";
  324. }
  325. }
  326. else if (type.IsClass && type != typeof(string))//枚举在类的属性中
  327. {
  328. if (schema.properties == null) return;
  329. var props = type.GetProperties();
  330. foreach (var prop in props)
  331. {
  332. var propScheama = schema.properties[prop.Name];
  333. if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string))
  334. {
  335. UpdateSchemaDescription(propScheama, prop.PropertyType);
  336. }
  337. else
  338. {
  339. if (prop.PropertyType.IsEnum)
  340. {
  341. var description = GetEnumInfo(prop.PropertyType);
  342. propScheama.description = string.IsNullOrWhiteSpace(propScheama.description) ? description : $"{propScheama.description}:{description}";
  343. propScheama.@enum = null;
  344. }
  345. }
  346. }
  347. }
  348. }
  349. /// <summary>
  350. /// 获取枚举值+描述
  351. /// </summary>
  352. /// <param name="enumType"></param>
  353. /// <returns></returns>
  354. private string GetEnumInfo(Type enumType)
  355. {
  356. var fields = enumType.GetFields();
  357. List<string> list = new List<string>();
  358. foreach (var field in fields)
  359. {
  360. if (!field.FieldType.IsEnum) continue;
  361. string description = null;
  362. if (description == null)//取DescriptionAttribute的值
  363. {
  364. var descriptionAttr = field.GetCustomAttribute<DescriptionAttribute>();
  365. if (descriptionAttr != null && !string.IsNullOrWhiteSpace(descriptionAttr.Description))
  366. {
  367. description = descriptionAttr.Description;
  368. }
  369. }
  370. if (description == null)//取DisplayAttribute的值
  371. {
  372. var dispalyAttr = field.GetCustomAttribute<DisplayAttribute>();
  373. if (dispalyAttr != null && !string.IsNullOrWhiteSpace(dispalyAttr.Name))
  374. {
  375. description = dispalyAttr.Name;
  376. }
  377. }
  378. if (description == null)//取DisplayNameAttribute的值
  379. {
  380. var dispalyNameAttr = field.GetCustomAttribute<DisplayNameAttribute>();
  381. if (dispalyNameAttr != null && !string.IsNullOrWhiteSpace(dispalyNameAttr.DisplayName))
  382. {
  383. description = dispalyNameAttr.DisplayName;
  384. }
  385. }
  386. if (description == null)//取字段名
  387. {
  388. description = field.Name;
  389. }
  390. var value = field.GetValue(null);
  391. list.Add($"{description}={(int)value}");
  392. }
  393. return string.Join(",", list);
  394. }
  395. }
  396. class CustomModelValidator : ModelValidator
  397. {
  398. public CustomModelValidator(IEnumerable<ModelValidatorProvider> modelValidatorProviders) : base(modelValidatorProviders)
  399. {
  400. }
  401. public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
  402. {
  403. if (metadata.IsComplexType && metadata.Model == null)
  404. {
  405. return new List<ModelValidationResult> { new ModelValidationResult { MemberName = metadata.GetDisplayName(), Message = "请求参数对象不能为空。" } };
  406. }
  407. if (typeof(IValidatableObject).IsAssignableFrom(metadata.ModelType))
  408. {
  409. var validationResult = (metadata.Model as IValidatableObject).Validate(new ValidationContext(metadata.Model));
  410. if (validationResult != null)
  411. {
  412. var modelValidationResults = new List<ModelValidationResult>();
  413. foreach (var result in validationResult)
  414. {
  415. modelValidationResults.Add(new ModelValidationResult
  416. {
  417. MemberName = string.Join(",", result.MemberNames),
  418. Message = result.ErrorMessage
  419. });
  420. }
  421. return modelValidationResults;
  422. }
  423. return null;
  424. }
  425. return GetModelValidator(ValidatorProviders).Validate(metadata, container);
  426. }
  427. }
  428. }