Startup.cs 28 KB

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