WebApi CustomModelBinder不对模型属性执行验证

时间:2016-06-02 10:15:26

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

我正在为我的webapi编写自定义模型绑定器。我试图获取查询字符串并填充模型属性。我得到了正确的模型,但它缺少模型属性的验证属性。谁能说出我做错了什么?在下面找到我的自定义模型活页夹和模型。

public class SearchCriteriaModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(SearchCriteria))
        {
            return false;
        }

        var searchCriteria = new SearchCriteria();
        var type = searchCriteria.GetType();

        var querystringVals = actionContext.Request.GetQueryNameValuePairs();
        var keyValuePairs = querystringVals as IList<KeyValuePair<string, string>> ?? querystringVals.ToList();
        if (!keyValuePairs.Any())
        {
            bindingContext.Model = searchCriteria;
            return true;
        }

        foreach (var value in keyValuePairs)
        {
            var key = value.Key;
            var prop = type.GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
            if (prop == null)
            {
                continue;
            }
            prop.SetValue(searchCriteria,value.Value);
        }

        bindingContext.Model = searchCriteria;

        return true;
    }
}


public class SearchCriteria
{
    public SearchCriteria()
    {
        Param1 = "";
        Param2 = "";
        PageIndex = 0;
        PageSize = 10;

    }
    public string Param1 { get; set; }
    public string Param2 { get; set; }
    public int PageIndex{ get; set; }
    public int PageSize { get; set; }
    [IsNumeric]
    publist string MinimumVal {get;set;}
}   

由于

1 个答案:

答案 0 :(得分:0)

Validator.TryValidateObject(..)将验证模型绑定器中的模型。

var validationResults = new Collection<ValidationResult>();
        var isValid = Validator.TryValidateObject(searchCriteria, new ValidationContext(searchCriteria, null, null), validationResults, true);
        if (!isValid)
        {
            foreach (var result in validationResults)
            {
                bindingContext.ModelState.AddModelError("", result.ErrorMessage);
            }
        }