saj*_*ith 5 c# asp.net asp.net-web-api asp.net-web-api2
我正在使用Web API 5构建Web Service。我正在通过扩展IModelBinder接口来实现将自定义模型绑定程序映射为操作的复杂类型。绑定部分工作正常。但是不会发生模型验证。ModelState.IsValid始终为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.
}
}
Run Code Online (Sandbox Code Playgroud)
如果我显式调用Validate()或使用[FromUri]属性,则将正确设置ModelState.IsValid。
public IEnumerable<NewsItemVM> Get([FromUri]PagingParamsVM pegination)
{
var valid = ModelState.IsValid;
}
Run Code Online (Sandbox Code Playgroud)
我应该在模型活页夹中实现验证部分吗?如果是这样,我应该如何实施?
我找到了答案。可以在自定义模型绑定器中调用默认验证过程,如下所示:
public abstract class PaginationModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var model = (PagingParamsVM)bindingContext.Model ?? new PagingParamsVM();
//model population logic
.....
bindingContext.Model = model;
//following lines invoke default validation on model
bindingContext.ValidationNode.ValidateAllProperties = true;
bindingContext.ValidationNode.Validate(actionContext);
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢大家的支持。