Startup.cs 28 KB

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