Explorar o código

feat: 😀增强EnumAttribute特性以支持可空枚举类型的验证

Ir0nMax hai 1 ano
pai
achega
4429eae0b8
Modificáronse 1 ficheiros con 7 adicións e 4 borrados
  1. 7 4
      Admin.NET/Admin.NET.Core/Attribute/EnumAttribute.cs

+ 7 - 4
Admin.NET/Admin.NET.Core/Attribute/EnumAttribute.cs

@@ -10,7 +10,7 @@ namespace Admin.NET.Core;
 /// 枚举值合规性校验特性
 /// </summary>
 [SuppressSniffer]
-[AttributeUsage( AttributeTargets.Property | AttributeTargets.Enum | AttributeTargets.Field, AllowMultiple = true)]
+[AttributeUsage(AttributeTargets.Property | AttributeTargets.Enum | AttributeTargets.Field, AllowMultiple = true)]
 public class EnumAttribute : ValidationAttribute, ITransient
 {
     /// <summary>
@@ -35,14 +35,17 @@ public class EnumAttribute : ValidationAttribute, ITransient
         if (property == null)
             return new ValidationResult($"未知属性: {validationContext.MemberName}");
 
-        var propertyType = property.PropertyType;
+        var propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
 
-        // 检查属性类型是否为枚举
+        // 检查属性类型是否为枚举或可空枚举类型
         if (!propertyType.IsEnum)
             return new ValidationResult($"属性类型'{validationContext.MemberName}'不是有效的枚举类型!");
 
         // 检查枚举值是否有效
-        if (!Enum.IsDefined(propertyType, value))
+        if (value == null && Nullable.GetUnderlyingType(property.PropertyType) == null)
+            return new ValidationResult($"提示:{ErrorMessage}|枚举值不能为 null!");
+
+        if (value != null && !Enum.IsDefined(propertyType, value))
             return new ValidationResult($"提示:{ErrorMessage}|枚举值【{value}】不是有效的【{propertyType.Name}】枚举类型值!");
 
         return ValidationResult.Success;