Web API:带有DataAnnotations的QueryString模型绑定规则

时间:2013-05-19 16:15:17

标签: query-string model-binding asp.net-web-api model-validation

我对如何在Web API中进行模型绑定,特别是模型验证感到困惑。我的大多数操作都通过POST请求接收对象,我的模型应用了各种ValidationAttributes,例如RequiredAttribute,MinLengthAttribute,StringLengthAttribute等。

然而,我的一个动作是GET请求,并且具有与此类似的签名:

public SearchResultCollection Search([FromUri]SearchRequest request)

最初看起来如下所示,但后来我发现你可以创建一个封装查询字符串中的参数的类:

public SearchResultCollection Search(string searchPath, string searchValue, int limit, string sortBy)

使用后者,我无法对参数进行任何形式的验证。例如,将RequiredAttribute应用于searchPath参数似乎什么也没做。这促使改变了动作签名,并创建了SearchRequest类,如下所示:

public class SearchRequest
{
    public SearchRequest()
    {
        SortBy = SearchSortingKey.Id;
    }

    [Required(ErrorMessage="A search path must be specified.")]
    public string SearchPath{ get; set; }

    [Required(ErrorMessage="A search value must be specified.")]
    public string SearchValue{ get; set; }

    [Required(ErrorMessage="A limit be specified.")]
    public int Limit { get; set; }

    public SearchSortingKey SortBy { get; set; }
}

使用此方法,似乎可以识别RequiredAttributes(它们导致模型验证失败),但执行模型验证时返回的错误消息不是我在上面的RequiredAttributes中指定的错误消息。

使用POST请求进行模型验证时,我没有遇到此问题,并且当模型通过查询字符串到达​​时,我不完全理解为什么它的行为不同。

有人可以对此有所了解吗?我想了解如何验证在查询字符串中传递的参数 - 我假设除了在操作体中执行验证之外还有其他一些方法。

我阅读了文章here,但它没有真正解释当模型进入查询字符串时模型验证的不同之处或原因。

1 个答案:

答案 0 :(得分:1)

您描述的问题是最近刚解决的ASP.NET WebApi中的错误。您可以在http://aspnetwebstack.codeplex.com/workitem/1471找到详细信息。

对于字符串属性,您应该能够使用[Required],但添加参数AllowEmptyStrings = false。我只需要解决非字符串属性的解决方法(如错误报告开发人员所述)。

如果你使用JSON进行反序列化,你可能想让你的int属性为空(int?);没有把它变成int? Newtonsoft.Json将属性的字符串转换为0。

/SearchRequest?SearchPath=[some string]&SearchValue=[some string]&SortBy=[some string]&Limit=