Rasmus
Rasmus

Reputation: 2933

WebApi, Custom model binder and Data annotations

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

Upvotes: 0

Views: 703

Answers (1)

Igor
Igor

Reputation: 381

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.

Upvotes: 1

Related Questions