EnumAttribute.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. namespace Admin.NET.Core;
  7. /// <summary>
  8. /// 枚举值合规性校验特性
  9. /// </summary>
  10. [SuppressSniffer]
  11. [AttributeUsage(AttributeTargets.Property | AttributeTargets.Enum | AttributeTargets.Field, AllowMultiple = true)]
  12. public class EnumAttribute : ValidationAttribute, ITransient
  13. {
  14. /// <summary>
  15. /// 枚举值合规性校验特性
  16. /// </summary>
  17. /// <param name="errorMessage"></param>
  18. public EnumAttribute(string errorMessage = "枚举值不合法!")
  19. {
  20. ErrorMessage = errorMessage;
  21. }
  22. /// <summary>
  23. /// 枚举值合规性校验
  24. /// </summary>
  25. /// <param name="value"></param>
  26. /// <param name="validationContext"></param>
  27. /// <returns></returns>
  28. protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  29. {
  30. // 获取属性的类型
  31. var property = validationContext.ObjectType.GetProperty(validationContext.MemberName);
  32. if (property == null)
  33. return new ValidationResult($"未知属性: {validationContext.MemberName}");
  34. var propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
  35. // 检查属性类型是否为枚举或可空枚举类型
  36. if (!propertyType.IsEnum)
  37. return new ValidationResult($"属性类型'{validationContext.MemberName}'不是有效的枚举类型!");
  38. // 检查枚举值是否有效
  39. if (value == null && Nullable.GetUnderlyingType(property.PropertyType) == null)
  40. return new ValidationResult($"提示:{ErrorMessage}|枚举值不能为 null!");
  41. if (value != null && !Enum.IsDefined(propertyType, value))
  42. return new ValidationResult($"提示:{ErrorMessage}|枚举值【{value}】不是有效的【{propertyType.Name}】枚举类型值!");
  43. return ValidationResult.Success;
  44. }
  45. }