Startup.cs 20 KB

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