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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With