Startup.cs 26 KB

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