0

So, is it possible to combine the 3?

When I send a request to the server that does not conform to the model annotated validation (empty email in this case) ModelState.IsValid is true.

Model

public class UpdateModel
{
    [Required]
    public string Email { get; set; }

    public string Name { get; set; }
}

Model Binder

public class MyModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var data = actionContext.Request.Content.ReadAsStringAsync().Result;
        var model = JsonConvert.DeserializeObject<UpdateModel>(data);
        bindingContext.Model = model;
        return true;
    }
}

Action in ApiController

public IHttpActionResult Update(UpdateModel model)
{
    if (!ModelState.IsValid)
    {
        // this never happens :-(
    }
}

Related but for MVC not WebApi: Custom model binding, model state, and data annotations

1 Answer 1

1

Validation through DataAnnotation was treated in Model Binder. If you use your own ModelBinder, you must explicit call validation over DataAnnotation in the ModelBinder - if you wish automatic validation over DA.

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.