Startup.cs 28 KB

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