Asp.net web api GET请求中绑定模型的Web API验证

Asp.net web api GET请求中绑定模型的Web API验证,asp.net-web-api,model-binding,url-parameters,Asp.net Web Api,Model Binding,Url Parameters,我已经创建了一个自定义模型绑定器,用于以特定格式从URI读取数据 public ResponseObject Get([FromUri(BinderType = typeof(CustomModelBinder)]ProductFilter product {...} public class ProductFilter { [Required(ErrorMessage = @"Name is required")] public string Name { get; set;

我已经创建了一个自定义模型绑定器,用于以特定格式从URI读取数据

public ResponseObject Get([FromUri(BinderType = typeof(CustomModelBinder)]ProductFilter product
{...}

public class ProductFilter
{
    [Required(ErrorMessage = @"Name is required")]
    public string Name { get; set; }
}

public class CustomModelBinder : IModelBinder
{
  public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
  {
      //Code to convert the uri parameters to object
      return true;
  }
}
在上面的示例中,我需要在执行操作之前从客户端传递名称。 但是,我无法使用此工具在产品类上运行内置验证?
有什么想法吗?

我在自定义操作筛选器中编写,并在所有服务的GlobalConfiguration中注册了此操作筛选器。动作过滤器钩住onActionExecuting,在绑定参数中查找验证

        bool isValid;
        foreach (var item in actionContext.ActionArguments)
        {
            var parameterValue = item.Value;

            var innerContext = new ValidationContext(parameterValue);
            if(parameterValue != null)
            {
                var innerContext = new ValidationContext(parameterValue);
                isValid = Validator.TryValidateObject(parameterValue, innerContext, results, true);
            }
        }
        //If not valid, throw a HttpResponseException
        if(!isValid)
             throw new HttpResponseException(HttpStatusCode.BadRequest);
        else
             base.onActionExecuting(actionContext);
通过更多的调优,可以从验证上下文中检索确切的验证消息,并将其作为响应消息发送

我还能够将其扩展到在参数本身上具有验证属性,从而为我的Api提供更大的灵活性