I'm building Web Service with Web API 5. I'm implementing custom model binder by extending IModelBinder interface to map complex type as a parameter to action. The binding part is working fine. But Model validation does not occur. ModelState.IsValid is always true.
public class PagingParamsVM
{
[Range(1, Int32.MaxValue, ErrorMessage = "Page must be at least 1")]
public int? Page { get; set; }
[Range(1, Int32.MaxValue, ErrorMessage = "Page size must be at least 1")]
public int? PageSize { get; set; }
}
public class PaginationModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var model = (PagingParamsVM)bindingContext.Model ?? new PagingParamsVM();
//model population logic
.....
bindingContext.Model = model;
return true;
}
}
public IEnumerable<NewsItemVM> Get([ModelBinder(typeof(PaginationModelBinder))]PagingParamsVM pegination)
{
//Validate(pegination); //if I call this explicitly ModelState.IsValid is set correctly.
var valid = ModelState.IsValid; //this is always true
}
public class ModelStateValidationActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var valid = actionContext.ModelState.IsValid //this is always true.
}
}
If I call Validate() explicitly or use [FromUri] attribute, ModelState.IsValid is set correctly.
public IEnumerable<NewsItemVM> Get([FromUri]PagingParamsVM pegination)
{
var valid = ModelState.IsValid;
}
Should I implement validation part inside model binder. If so how should I implement?