7

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.

2
  • Did you ever find a good solution? I'm thinking of decorating or subclassing the IModelBinder, but I'd like to know if there is a better way. Commented Nov 11, 2016 at 10:22
  • @FabianSchmied: Unfortunately no. The "Web API" model binder probably has better support for this case - and I don't know about ASP.NET Core. Commented Nov 14, 2016 at 5:51

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.