Startup.cs 24 KB

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