Startup.cs 27 KB

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