Startup.cs 27 KB

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