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

ASP.NET Core Web API:如何查找属性未通过的数据注解

如何定位EmailAddress属性未通过的验证注解

当ModelState.IsValid为false时,你可以通过以下两种方式获取EmailAddress属性具体的验证失败项:

方法一:通过错误消息直接匹配验证注解

直接读取ModelState中该属性的错误集合,每个错误的提示信息对应你在验证注解中定义的ErrorMessage,以此判断具体未通过的验证:

if (!ModelState.IsValid)
{
    var emailErrorList = ModelState["EmailAddress"].Errors;
    foreach (var error in emailErrorList)
    {
        string failedValidation = error.ErrorMessage switch
        {
            "The Email Address is not valid." => "EmailAddress 格式验证失败",
            "The Email Address must be less than 5 characters." => "StringLength 长度验证失败",
            _ => "未知验证规则失败"
        };
        // 这里可以记录或返回该验证失败信息
    }
}

方法二:通过反射匹配验证注解类型

若不想硬编码错误消息,可通过反射获取属性上的所有验证注解,再结合ModelState的错误信息匹配:

if (!ModelState.IsValid)
{
    // 获取User类中EmailAddress属性的所有验证注解
    var emailProperty = typeof(User).GetProperty(nameof(User.EmailAddress));
    var allValidationAttrs = emailProperty.GetCustomAttributes<ValidationAttribute>();
    
    // 获取该属性的所有错误消息
    var emailErrorMessages = ModelState["EmailAddress"].Errors.Select(e => e.ErrorMessage).ToList();
    
    foreach (var attr in allValidationAttrs)
    {
        if (emailErrorMessages.Contains(attr.ErrorMessage))
        {
            // attr即为未通过的验证注解,比如EmailAddressAttribute、StringLengthAttribute
            string failedAttrType = attr.GetType().Name;
            // 处理或记录该验证失败类型
        }
    }
}

注意事项

  • 确保代码中没有手动清除ModelState的错误记录,否则会丢失验证信息
  • 自定义验证注解也可通过上述两种方式定位失败项

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:07:27