c# - Web API 验证不会使用自定义模型 Binder 触发

标签 c# asp.net asp.net-web-api asp.net-web-api2

我正在使用 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/

相关文章:

c# - ASP.NET Core Web API 自动 JSON 参数反序列化不起作用

用于法国文化的 C# float.tryparse

c# - 获得授权属性的许可?

asp.net - 如何将 If...Then 逻辑复制为 Web 控件?

c# - 在Ext.Net按钮上调用ASP.net事件处理程序单击

c# - 具有路由属性的模糊 Controller 名称 : controllers with same name and different namespace for versioning

c# - 使用 log4net 时记录异常的最佳方式是什么

c# - ScriptControlDescriptor.AddProperty 和只读属性

asp.net - 用户控件引用父用户控件中的 usercontrol 时出现 NullReferenceException

c# - 如何在不创建新刷新 token 的情况下使用刷新 token 更新 Owin 访问 token ?