You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core中Model Validation的DataAnnotations执行顺序是否与声明一致?

.NET Core DataAnnotations 模型验证的执行顺序

.NET Core 中,DataAnnotations 的验证默认不保证与声明顺序一致,它的执行顺序属于未定义行为,不能依赖代码里的注解排列顺序来控制验证流程。

以你给出的示例代码为例:

public class Model1
{
     [Required]
     [Range(3,45,ErrorMessage="out of range")]
     [EmailAddress]
     public string email_id {get;set;}
}

这里的[Required]、[Range]、[EmailAddress]三个注解,不会严格按照你写的顺序执行检查。默认验证系统通过反射获取属性上的验证注解,但没有明确的排序逻辑,不同场景或.NET版本下,执行顺序可能发生变化。

如果业务逻辑要求必须按特定顺序执行验证,不要依赖DataAnnotations的声明顺序,建议实现IValidatableObject接口,手动控制验证步骤:

public class Model1 : IValidatableObject
{
    public string email_id { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        // 按需求顺序执行验证
        if (string.IsNullOrEmpty(email_id))
        {
            yield return new ValidationResult("The email_id field is required.", new[] { nameof(email_id) });
        }
        else if (email_id.Length < 3 || email_id.Length > 45)
        {
            yield return new ValidationResult("out of range", new[] { nameof(email_id) });
        }
        else if (!new EmailAddressAttribute().IsValid(email_id))
        {
            yield return new ValidationResult("The email_id field is not a valid email address.", new[] { nameof(email_id) });
        }
    }
}

内容的提问来源于stack exchange,提问作者Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:40:48