Startup.cs 28 KB

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