Startup.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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",
  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. builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
  135. //将程序集中的所有Service注入到容器
  136. var serviceTypes = Assembly.GetExecutingAssembly().GetTypes().Where(p => p.Namespace != null && p.Namespace.EndsWith(".Service")).ToList();
  137. foreach (var serviceType in serviceTypes)
  138. {
  139. //单例模式注入Service
  140. builder.RegisterTypes(serviceType).SingleInstance();
  141. }
  142. var container = builder.Build();
  143. config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
  144. app.UseAutofacLifetimeScopeInjector(container);
  145. app.UseAutofacMiddleware(container);
  146. app.UseAutofacWebApi(config);
  147. app.UseCors(CorsOptions.AllowAll);
  148. app.UseWebApi(config);
  149. }
  150. private static void ConfigureSwagger(HttpConfiguration config)
  151. {
  152. var thisAssembly = typeof(Startup).Assembly;
  153. config.EnableSwagger(c =>
  154. {
  155. c.IgnoreObsoleteActions();//忽略过时的方法
  156. c.IgnoreObsoleteProperties();//忽略过时的属性
  157. c.PrettyPrint();//漂亮缩进
  158. c.SingleApiVersion("v1", "多模式融合定位平台Http接口");
  159. c.ApiKey("123456");
  160. var webApiXmlPath1 = $"{AppDomain.CurrentDomain.BaseDirectory}{Path.GetFileNameWithoutExtension(_dtoXmlName)}.xml";
  161. c.IncludeXmlComments(webApiXmlPath1);//dto模型描述
  162. var webApiXmlPath2 = $"{AppDomain.CurrentDomain.BaseDirectory}{Path.GetFileNameWithoutExtension(_controllerXmlName)}.xml";
  163. c.IncludeXmlComments(webApiXmlPath2);//控制器中方法描述
  164. var webApiXmlPath3 = $"{AppDomain.CurrentDomain.BaseDirectory}{typeof(AjaxResult).Assembly.GetName().Name}.xml";
  165. c.IncludeXmlComments(webApiXmlPath3);//返回值描述
  166. //控制器本身描述
  167. string controllerXmlPath= $"{AppDomain.CurrentDomain.BaseDirectory}{Path.GetFileNameWithoutExtension(_controllerXmlName)}.xml";
  168. c.CustomProvider(defaultProvider => new SwaggerControllerDescProvider(defaultProvider, controllerXmlPath));
  169. c.OperationFilter<FileUploadOperation>();
  170. c.SchemaFilter<SwaggerEnumFilter>();
  171. c.SchemaFilter<SwaggerDefalutValueFilter>();
  172. })
  173. .EnableSwaggerUi(c =>
  174. {
  175. c.InjectJavaScript(thisAssembly, $"{Assembly.GetExecutingAssembly().GetName().Name}.Swagger.js");
  176. c.DocumentTitle("多模式融合定位平台Http接口");
  177. });
  178. }
  179. class FileUploadOperation : IOperationFilter
  180. {
  181. public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
  182. {
  183. if (operation.parameters == null)
  184. {
  185. operation.parameters = new List<Swashbuckle.Swagger.Parameter>();
  186. }
  187. var requestAttributes = apiDescription.GetControllerAndActionAttributes<SwaggerFormAttribute>();
  188. foreach (var attr in requestAttributes)
  189. {
  190. operation.parameters.Add(new Swashbuckle.Swagger.Parameter
  191. {
  192. description = attr.Description,
  193. name = attr.Name,
  194. @in = "formData",
  195. required = true,
  196. type = "file",
  197. });
  198. operation.consumes.Add("multipart/form-data");
  199. }
  200. }
  201. }
  202. class ValidateFilter : IActionFilter
  203. {
  204. public bool AllowMultiple { get; }
  205. public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
  206. {
  207. if (!actionContext.ModelState.IsValid)
  208. {
  209. string msg = "";
  210. var err = actionContext.ModelState.Values?.Last()?.Errors?.Last();
  211. if (err != null)
  212. {
  213. if (!string.IsNullOrWhiteSpace(err.ErrorMessage))
  214. msg = err.ErrorMessage;
  215. else
  216. msg = err.Exception.Message;
  217. }
  218. return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
  219. {
  220. Content = new StringContent(
  221. JsonConvert.SerializeObject(
  222. new AjaxResult
  223. {
  224. code = 0,
  225. data = null,
  226. msg = msg,
  227. }), Encoding.UTF8, "application/json")
  228. });
  229. }
  230. return continuation();
  231. }
  232. }
  233. class HandlerErrorAttribute : ExceptionFilterAttribute
  234. {
  235. /// <summary>
  236. /// 控制器方法中出现异常,会调用该方法捕获异常
  237. /// </summary>
  238. /// <param name="context">提供使用</param>
  239. public override void OnException(HttpActionExecutedContext context)
  240. {
  241. if (context.Exception.GetType() != typeof(System.OperationCanceledException))
  242. Serilog.Log.Error(context.Exception, context.Exception.Message);
  243. else
  244. return;
  245. base.OnException(context);
  246. string msg = context.Exception.Message;
  247. if (context.Exception.GetType() == typeof(FileNotFoundException))
  248. {
  249. //防止程序路径泄露到前端
  250. msg = "未能找到文件" + context.Exception.Message.Substring(context.Exception.Message.LastIndexOf("\\") + 1);
  251. }
  252. throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.OK)
  253. {
  254. Content = new StringContent(
  255. JsonConvert.SerializeObject(
  256. new AjaxResult
  257. {
  258. code = 0,
  259. data = null,
  260. msg = msg
  261. }), Encoding.UTF8, "application/json")
  262. });
  263. }
  264. };
  265. class SwaggerControllerDescProvider : ISwaggerProvider
  266. {
  267. private readonly ISwaggerProvider _swaggerProvider;
  268. private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>();
  269. private readonly string _xml;
  270. /// <summary>
  271. ///
  272. /// </summary>
  273. /// <param name="swaggerProvider"></param>
  274. /// <param name="xml">xml文档路径</param>
  275. public SwaggerControllerDescProvider(ISwaggerProvider swaggerProvider, string xml)
  276. {
  277. _swaggerProvider = swaggerProvider;
  278. _xml = xml;
  279. }
  280. public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
  281. {
  282. var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion);
  283. SwaggerDocument srcDoc = null;
  284. //只读取一次
  285. if (!_cache.TryGetValue(cacheKey, out srcDoc))
  286. {
  287. srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion);
  288. srcDoc.vendorExtensions = new Dictionary<string, object> { { "ControllerDesc", GetControllerDesc() } };
  289. _cache.TryAdd(cacheKey, srcDoc);
  290. }
  291. return srcDoc;
  292. }
  293. /// <summary>
  294. /// 从API文档中读取控制器描述
  295. /// </summary>
  296. /// <returns>所有控制器描述</returns>
  297. public ConcurrentDictionary<string, string> GetControllerDesc()
  298. {
  299. string xmlpath = _xml;
  300. ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>();
  301. if (File.Exists(xmlpath))
  302. {
  303. XmlDocument xmldoc = new XmlDocument();
  304. xmldoc.Load(xmlpath);
  305. string type = string.Empty, path = string.Empty, controllerName = string.Empty;
  306. string[] arrPath;
  307. int length = -1, cCount = "Controller".Length;
  308. XmlNode summaryNode = null;
  309. foreach (XmlNode node in xmldoc.SelectNodes("//member"))
  310. {
  311. type = node.Attributes["name"].Value;
  312. if (type.StartsWith("T:"))
  313. {
  314. //控制器
  315. arrPath = type.Split('.');
  316. length = arrPath.Length;
  317. controllerName = arrPath[length - 1];
  318. if (controllerName.EndsWith("Controller"))
  319. {
  320. //获取控制器注释
  321. summaryNode = node.SelectSingleNode("summary");
  322. string key = controllerName.Remove(controllerName.Length - cCount, cCount);
  323. if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key))
  324. {
  325. controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim());
  326. }
  327. }
  328. }
  329. }
  330. }
  331. return controllerDescDict;
  332. }
  333. }
  334. }
  335. /// <summary>
  336. /// Swagger文件上传特性标注
  337. /// </summary>
  338. [AttributeUsage(AttributeTargets.Method)]
  339. public sealed class SwaggerFormAttribute : Attribute
  340. {
  341. /// <summary>
  342. ///
  343. /// </summary>
  344. public SwaggerFormAttribute()
  345. {
  346. this.Name = "文件";
  347. this.Description = "选择文件";
  348. }
  349. /// <summary>
  350. /// Swagger特性标注
  351. /// </summary>
  352. /// <param name="name"></param>
  353. /// <param name="description"></param>
  354. public SwaggerFormAttribute(string name, string description)
  355. {
  356. Name = name;
  357. Description = description;
  358. }
  359. /// <summary>
  360. /// 名称
  361. /// </summary>
  362. public string Name { get; private set; }
  363. /// <summary>
  364. /// 描述
  365. /// </summary>
  366. public string Description { get; private set; }
  367. }
  368. /// <summary>
  369. /// autofac属性注入
  370. /// </summary>
  371. [AttributeUsage(AttributeTargets.Property)]
  372. public class AutowiredAttribute : Attribute
  373. {
  374. }
  375. // 属性注入选择器
  376. class AutowiredPropertySelector : IPropertySelector
  377. {
  378. public bool InjectProperty(PropertyInfo propertyInfo, object instance)
  379. {
  380. // 带有 AutowiredAttribute 特性的属性会进行属性注入
  381. return propertyInfo.CustomAttributes.Any(it => it.AttributeType == typeof(AutowiredAttribute));
  382. }
  383. }
  384. class SwaggerEnumFilter : ISchemaFilter
  385. {
  386. public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
  387. {
  388. UpdateSchemaDescription(schema, type);
  389. }
  390. private void UpdateSchemaDescription(Schema schema, Type type)
  391. {
  392. if (type.IsEnum)//枚举直接应用在controller接口中
  393. {
  394. var items = GetEnumInfo(type);
  395. if (items.Length > 0)
  396. {
  397. var description = GetEnumInfo(type);
  398. schema.description = string.IsNullOrEmpty(schema.description) ? description : $"{schema.description}:{description}";
  399. }
  400. }
  401. else if (type.IsClass && type != typeof(string))//枚举在类的属性中
  402. {
  403. if (schema.properties == null) return;
  404. var props = type.GetProperties();
  405. foreach (var prop in props)
  406. {
  407. var propScheama = schema.properties[prop.Name];
  408. if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string))
  409. {
  410. UpdateSchemaDescription(propScheama, prop.PropertyType);
  411. }
  412. else
  413. {
  414. if (prop.PropertyType.IsEnum)
  415. {
  416. var description = GetEnumInfo(prop.PropertyType);
  417. propScheama.description = string.IsNullOrWhiteSpace(propScheama.description) ? description : $"{propScheama.description}:{description}";
  418. propScheama.@enum = null;
  419. }
  420. }
  421. }
  422. }
  423. }
  424. /// <summary>
  425. /// 获取枚举值+描述
  426. /// </summary>
  427. /// <param name="enumType"></param>
  428. /// <returns></returns>
  429. private string GetEnumInfo(Type enumType)
  430. {
  431. var fields = enumType.GetFields();
  432. List<string> list = new List<string>();
  433. foreach (var field in fields)
  434. {
  435. if (!field.FieldType.IsEnum) continue;
  436. string description = null;
  437. if (description == null)//取DescriptionAttribute的值
  438. {
  439. var descriptionAttr = field.GetCustomAttribute<DescriptionAttribute>();
  440. if (descriptionAttr != null && !string.IsNullOrWhiteSpace(descriptionAttr.Description))
  441. {
  442. description = descriptionAttr.Description;
  443. }
  444. }
  445. if (description == null)//取DisplayAttribute的值
  446. {
  447. var dispalyAttr = field.GetCustomAttribute<DisplayAttribute>();
  448. if (dispalyAttr != null && !string.IsNullOrWhiteSpace(dispalyAttr.Name))
  449. {
  450. description = dispalyAttr.Name;
  451. }
  452. }
  453. if (description == null)//取DisplayNameAttribute的值
  454. {
  455. var dispalyNameAttr = field.GetCustomAttribute<DisplayNameAttribute>();
  456. if (dispalyNameAttr != null && !string.IsNullOrWhiteSpace(dispalyNameAttr.DisplayName))
  457. {
  458. description = dispalyNameAttr.DisplayName;
  459. }
  460. }
  461. if (description == null)//取字段名
  462. {
  463. description = field.Name;
  464. }
  465. var value = field.GetValue(null);
  466. list.Add($"{description}={(int)value}");
  467. }
  468. return string.Join(",", list);
  469. }
  470. }
  471. class CustomModelValidator : ModelValidator
  472. {
  473. public CustomModelValidator(IEnumerable<ModelValidatorProvider> modelValidatorProviders) : base(modelValidatorProviders)
  474. {
  475. }
  476. public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
  477. {
  478. if (metadata.IsComplexType && metadata.Model == null)
  479. {
  480. return new List<ModelValidationResult> { new ModelValidationResult { MemberName = metadata.GetDisplayName(), Message = "请求参数对象不能为空" } };
  481. }
  482. if (typeof(IValidatableObject).IsAssignableFrom(metadata.ModelType))
  483. {
  484. var validationResult = (metadata.Model as IValidatableObject).Validate(new ValidationContext(metadata.Model));
  485. if (validationResult != null)
  486. {
  487. var modelValidationResults = new List<ModelValidationResult>();
  488. foreach (var result in validationResult)
  489. {
  490. if (result == null) continue;
  491. modelValidationResults.Add(new ModelValidationResult
  492. {
  493. MemberName = string.Join(",", result.MemberNames),
  494. Message = result.ErrorMessage
  495. });
  496. }
  497. return modelValidationResults;
  498. }
  499. return null;
  500. }
  501. return GetModelValidator(ValidatorProviders).Validate(metadata, container);
  502. }
  503. }
  504. class SwaggerDefalutValueFilter : ISchemaFilter
  505. {
  506. public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
  507. {
  508. if (schema.properties == null)
  509. {
  510. return;
  511. }
  512. var props = type.GetProperties().Where(p => p.PropertyType == typeof(DateTime) || p.PropertyType == typeof(DateTime?));
  513. foreach (PropertyInfo propertyInfo in props)
  514. {
  515. foreach (KeyValuePair<string, Schema> property in schema.properties)
  516. {
  517. if (propertyInfo.Name == property.Key)
  518. {
  519. property.Value.example = "2023-05-12 12:00:00";
  520. break;
  521. }
  522. }
  523. }
  524. }
  525. }
  526. }