我正在使用 Web API 5 构建 Web 服务。我正在通过扩展 IModelBinder 接口(interface)以将复杂类型作为参数映射到操作来实现自定义模型联编程序。绑定(bind)部分工作正常。但是不会进行模型验证。 ModelState.IsValid 始终为真。
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.
}
}
如果我显式调用 Validate() 或使用 [FromUri] 属性,则 ModelState.IsValid 设置正确。
public IEnumerable<NewsItemVM> Get([FromUri]PagingParamsVM pegination)
{
var valid = ModelState.IsValid;
}
我应该在模型绑定(bind)器中实现验证部分吗?如果是这样我应该如何实现?
最佳答案
我找到了答案。可以在自定义模型绑定(bind)器中调用默认验证过程,如下所示,
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;
}
}
谢谢大家的支持。
关于c# - Web API 验证不会使用自定义模型 Binder 触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40968811/