Startup.cs 19 KB

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