GET请求中模型绑定的Web API验证

时间:2014-12-22 21:46:09

标签: asp.net-web-api model-binding url-parameters

我创建了一个自定义Model Binder,以特定格式从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;
  }
}

在上面的例子中,我需要在执行Action之前从客户端传递名称。 但是,我无法使用此方法在Product类上运行内置验证? 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我在自定义操作过滤器中写道,我在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提供更大的灵活性