Startup.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. if (context.Exception.GetType() != typeof(System.OperationCanceledException))
  267. Serilog.Log.Error(context.Exception, context.Exception.Message);
  268. else
  269. return;
  270. base.OnException(context);
  271. string msg = context.Exception.Message;
  272. if (context.Exception.GetType() == typeof(FileNotFoundException))
  273. {
  274. //防止程序路径泄露到前端
  275. msg = "未能找到文件" + context.Exception.Message.Substring(context.Exception.Message.LastIndexOf("\\") + 1);
  276. }
  277. throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.OK)
  278. {
  279. Content = new StringContent(
  280. JsonConvert.SerializeObject(
  281. new AjaxResult
  282. {
  283. code = 0,
  284. data = null,
  285. msg = msg
  286. }), Encoding.UTF8, "application/json")
  287. });
  288. }
  289. };
  290. class SwaggerControllerDescProvider : ISwaggerProvider
  291. {
  292. private readonly ISwaggerProvider _swaggerProvider;
  293. private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>();
  294. private readonly string[] _xml;
  295. /// <summary>
  296. ///
  297. /// </summary>
  298. /// <param name="swaggerProvider"></param>
  299. /// <param name="xml">xml文档路径</param>
  300. public SwaggerControllerDescProvider(ISwaggerProvider swaggerProvider, string[] xml)
  301. {
  302. _swaggerProvider = swaggerProvider;
  303. _xml = xml;
  304. }
  305. public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
  306. {
  307. var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion);
  308. SwaggerDocument srcDoc = null;
  309. //只读取一次
  310. if (!_cache.TryGetValue(cacheKey, out srcDoc))
  311. {
  312. srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion);
  313. srcDoc.vendorExtensions = new Dictionary<string, object> { { "ControllerDesc", GetControllerDesc() } };
  314. _cache.TryAdd(cacheKey, srcDoc);
  315. }
  316. return srcDoc;
  317. }
  318. /// <summary>
  319. /// 从API文档中读取控制器描述
  320. /// </summary>
  321. /// <returns>所有控制器描述</returns>
  322. public ConcurrentDictionary<string, string> GetControllerDesc()
  323. {
  324. ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>();
  325. if (_xml != null)
  326. {
  327. foreach (var item in _xml)
  328. {
  329. if (File.Exists(item))
  330. {
  331. XmlDocument xmldoc = new XmlDocument();
  332. xmldoc.Load(item);
  333. string type = string.Empty, path = string.Empty, controllerName = string.Empty;
  334. string[] arrPath;
  335. int length = -1, cCount = "Controller".Length;
  336. XmlNode summaryNode = null;
  337. foreach (XmlNode node in xmldoc.SelectNodes("//member"))
  338. {
  339. type = node.Attributes["name"].Value;
  340. if (type.StartsWith("T:"))
  341. {
  342. //控制器
  343. arrPath = type.Split('.');
  344. length = arrPath.Length;
  345. controllerName = arrPath[length - 1];
  346. if (controllerName.EndsWith("Controller"))
  347. {
  348. //获取控制器注释
  349. summaryNode = node.SelectSingleNode("summary");
  350. string key = controllerName.Remove(controllerName.Length - cCount, cCount);
  351. if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key))
  352. {
  353. controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim());
  354. }
  355. }
  356. }
  357. }
  358. }
  359. }
  360. }
  361. return controllerDescDict;
  362. }
  363. }
  364. }
  365. /// <summary>
  366. /// Swagger文件上传特性标注
  367. /// </summary>
  368. [AttributeUsage(AttributeTargets.Method)]
  369. public sealed class SwaggerFormAttribute : Attribute
  370. {
  371. /// <summary>
  372. ///
  373. /// </summary>
  374. public SwaggerFormAttribute()
  375. {
  376. this.Name = "文件";
  377. this.Description = "选择文件";
  378. }
  379. /// <summary>
  380. /// Swagger特性标注
  381. /// </summary>
  382. /// <param name="name"></param>
  383. /// <param name="description"></param>
  384. public SwaggerFormAttribute(string name, string description)
  385. {
  386. Name = name;
  387. Description = description;
  388. }
  389. /// <summary>
  390. /// 名称
  391. /// </summary>
  392. public string Name { get; private set; }
  393. /// <summary>
  394. /// 描述
  395. /// </summary>
  396. public string Description { get; private set; }
  397. }
  398. /// <summary>
  399. /// autofac属性注入
  400. /// </summary>
  401. [AttributeUsage(AttributeTargets.Property)]
  402. public class AutowiredAttribute : Attribute
  403. {
  404. }
  405. // 属性注入选择器
  406. class AutowiredPropertySelector : IPropertySelector
  407. {
  408. public bool InjectProperty(PropertyInfo propertyInfo, object instance)
  409. {
  410. // 带有 AutowiredAttribute 特性的属性会进行属性注入
  411. return propertyInfo.CustomAttributes.Any(it => it.AttributeType == typeof(AutowiredAttribute));
  412. }
  413. }
  414. class SwaggerEnumFilter : ISchemaFilter
  415. {
  416. public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
  417. {
  418. UpdateSchemaDescription(schema, type);
  419. }
  420. private void UpdateSchemaDescription(Schema schema, Type type)
  421. {
  422. if (type.IsEnum)//枚举直接应用在controller接口中
  423. {
  424. var items = GetEnumInfo(type);
  425. if (items.Length > 0)
  426. {
  427. var description = GetEnumInfo(type);
  428. schema.description = string.IsNullOrEmpty(schema.description) ? description : $"{schema.description}:{description}";
  429. }
  430. }
  431. else if (type.IsClass && type != typeof(string))//枚举在类的属性中
  432. {
  433. if (schema.properties == null) return;
  434. var props = type.GetProperties();
  435. foreach (var prop in props)
  436. {
  437. if (schema.properties.ContainsKey(prop.Name))
  438. {
  439. var propScheama = schema.properties[prop.Name];
  440. if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string))
  441. {
  442. UpdateSchemaDescription(propScheama, prop.PropertyType);
  443. }
  444. else
  445. {
  446. if (prop.PropertyType.IsEnum)
  447. {
  448. var description = GetEnumInfo(prop.PropertyType);
  449. propScheama.description = string.IsNullOrWhiteSpace(propScheama.description) ? description : $"{propScheama.description}:{description}";
  450. propScheama.@enum = null;
  451. }
  452. }
  453. }
  454. }
  455. }
  456. }
  457. /// <summary>
  458. /// 获取枚举值+描述
  459. /// </summary>
  460. /// <param name="enumType"></param>
  461. /// <returns></returns>
  462. private string GetEnumInfo(Type enumType)
  463. {
  464. var fields = enumType.GetFields();
  465. List<string> list = new List<string>();
  466. foreach (var field in fields)
  467. {
  468. if (!field.FieldType.IsEnum) continue;
  469. string description = null;
  470. if (description == null)//取DescriptionAttribute的值
  471. {
  472. var descriptionAttr = field.GetCustomAttribute<DescriptionAttribute>();
  473. if (descriptionAttr != null && !string.IsNullOrWhiteSpace(descriptionAttr.Description))
  474. {
  475. description = descriptionAttr.Description;
  476. }
  477. }
  478. if (description == null)//取DisplayAttribute的值
  479. {
  480. var dispalyAttr = field.GetCustomAttribute<DisplayAttribute>();
  481. if (dispalyAttr != null && !string.IsNullOrWhiteSpace(dispalyAttr.Name))
  482. {
  483. description = dispalyAttr.Name;
  484. }
  485. }
  486. if (description == null)//取DisplayNameAttribute的值
  487. {
  488. var dispalyNameAttr = field.GetCustomAttribute<DisplayNameAttribute>();
  489. if (dispalyNameAttr != null && !string.IsNullOrWhiteSpace(dispalyNameAttr.DisplayName))
  490. {
  491. description = dispalyNameAttr.DisplayName;
  492. }
  493. }
  494. if (description == null)//取字段名
  495. {
  496. description = field.Name;
  497. }
  498. var value = field.GetValue(null);
  499. list.Add($"{description}={(int)value}");
  500. }
  501. if (enumType.GetCustomAttribute<FlagsAttribute>() != null)//支持按位与的枚举
  502. {
  503. list.Add("(多个类型请将对应数字相加)");
  504. }
  505. return string.Join(",", list);
  506. }
  507. }
  508. class CustomModelValidator : ModelValidator
  509. {
  510. public CustomModelValidator(IEnumerable<ModelValidatorProvider> modelValidatorProviders) : base(modelValidatorProviders)
  511. {
  512. }
  513. public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
  514. {
  515. if (metadata.IsComplexType && metadata.Model == null)
  516. {
  517. return new List<ModelValidationResult> { new ModelValidationResult { MemberName = metadata.GetDisplayName(), Message = "请求参数对象不能为空" } };
  518. }
  519. if (typeof(IValidatableObject).IsAssignableFrom(metadata.ModelType))
  520. {
  521. var validationResult = (metadata.Model as IValidatableObject).Validate(new ValidationContext(metadata.Model));
  522. if (validationResult != null)
  523. {
  524. var modelValidationResults = new List<ModelValidationResult>();
  525. foreach (var result in validationResult)
  526. {
  527. if (result == null) continue;
  528. modelValidationResults.Add(new ModelValidationResult
  529. {
  530. MemberName = string.Join(",", result.MemberNames),
  531. Message = result.ErrorMessage
  532. });
  533. }
  534. return modelValidationResults;
  535. }
  536. return null;
  537. }
  538. return GetModelValidator(ValidatorProviders).Validate(metadata, container);
  539. }
  540. }
  541. class SwaggerDefalutValueFilter : ISchemaFilter
  542. {
  543. public SwaggerDefalutValueFilter()
  544. {
  545. var cc = this.GetHashCode();
  546. }
  547. public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
  548. {
  549. if (schema.properties == null)
  550. {
  551. return;
  552. }
  553. var props = type.GetProperties().Where(p => p.PropertyType == typeof(DateTime) || p.PropertyType == typeof(DateTime?));
  554. var props2 = type.GetProperties().Where(p => p.PropertyType == typeof(DateTimeOffset) || p.PropertyType == typeof(DateTimeOffset?));
  555. foreach (PropertyInfo propertyInfo in props)
  556. {
  557. foreach (KeyValuePair<string, Schema> property in schema.properties)
  558. {
  559. if (propertyInfo.Name == property.Key)
  560. {
  561. property.Value.example = "2023-05-12 12:00:00";
  562. if (!string.IsNullOrWhiteSpace(Startup._timeZoneUtc) && propertyInfo.Name.EndsWith("Time"))
  563. {
  564. property.Value.description = $"{property.Value.description}({Startup._timeZoneUtc})";
  565. }
  566. else
  567. {
  568. }
  569. break;
  570. }
  571. }
  572. }
  573. foreach (PropertyInfo propertyInfo in props2)
  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 +0800";
  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. }
  592. }
  593. }