Startup.cs 24 KB

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