Reliably handle ASP.NET MVC model binding errors

I'm developing a REST API using MVC controllers. I'd like to handle all model binding errors and report them to the client in a user-friendly way. In my custom model binders I'm already throwing a special exception that's considered safe by the exception handler and shown to the client.

However, when the default model binder sees an invalid value (say, asdf for an int ) it seems to either completely ignore it (if the parameter's not required) or throw a plain ArgumentException (if the parameter is required). Is it possible to reliably handle both cases and get the name of the parameter and the related error, without rewriting the entire binder by hand?

I'd rather not show the ArgumentException as is because it reveals method and namespace names which the client shouldn't have to care about. I'd also rather not parse the ArgumentException message if it's avoidable, and that wouldn't solve the problem with invalid values for non-required parameters being ignored completely.


You could implement the IValidatableObject interface on your model. There you can create your own validation logic, replacing the Required attribute validation you currently have.

public class Model : IValidatableObject {
    public int MyIntProperty { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
        if (MyIntProperty == 0) {
            yield return new ValidationResult("Please provide a valid value for MyIntProperty.", new[] { "MyIntProperty" });
        }
    }
}

In your controller you can inspect the ModelState.Errors collection to see the validation errors. Also, this will generate the error CSS class on the client side provided you're using a strongly typed view and the HTML form helpers.

链接地址: http://www.djcxy.com/p/9998.html

上一篇: 尝试将蓝牙套接字绑定到PSM 17和19时,MeeGo上会返回EACCESS

下一篇: 可靠地处理ASP.NET MVC模型绑定错误