如何确定哪个ValidationAttribute导致了Model错误

6

我遇到了一个问题,我想确定哪个ValidationAttribute返回了特定的ModelError。我在我的Web API中有一个端点,它接受这样一个模型:

public class MyClass
{
    [Required]
    [Range(0, 3)]
    public int? Number { get; set; }

    [Required]
    [Range(0, 3)]
    public int? NumberTwo { get; set; }
}

并添加一个筛选器来检查ModelState是否有效;

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            IEnumerable<ModelError> errors = actionContext.ModelState.Values.SelectMany(s => s.Errors);
            // ...
        }
    }
}

我看到ModelError有两个属性:ErrorMessage是字符串类型,Exception是异常类型。我想要一种强类型的方法来确定哪个ValidationAttribute(例如[Required]或[Range(0, 3)])返回了错误响应,而不进行字符串操作。是否有一种使用这些属性返回自定义属性的方法我不熟悉?
如果客户端提交了这样的模型:
{
    "NumberTwo":10
}

最终目标是从API中产生以下类似的响应;
{
    "supportCode" : "1234567890",
    "errors" : [{
        "code" : "Missing",
        "message" : "The Number field is required."
    }, {
        "code" : "Invalid",
        "message" : "The field NumberTwo must be between 0 and 3."
    }] 
}
1个回答

0

如果您编写自己的验证程序而不是使用MVC中内置的程序,则可能实现。您需要在每个属性上使用反射,然后在每个属性上的每个验证属性上使用反射。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接