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

Community
  • 1
  • 1
Rasmus
  • 2,783
  • 2
  • 33
  • 43

1 Answers1

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.

Igor
  • 381
  • 3
  • 17