1

我對Web API中如何進行模型綁定以及特定模型驗證感到非常困惑。我的大部分操作都通過POST請求接收對象,而我的模型具有應用於它們的各種ValidationAttributes,例如RequiredAttribute,MinLengthAttribute,StringLengthAttribute等。Web API:使用DataAnnotations的QueryString模型綁定規則

但是,我的一個操作是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這篇文章,但它並沒有真正解釋模型驗證在模型進入查詢字符串時的方式和原因。

+0

老帖子,但對於其他人誰越過它絆倒。看來這是一個剛剛解決的錯誤; [問題詳情](http://aspnetwebstack.codeplex.com/workitem/1471) – emgee

+0

哦,真的嗎?你有鏈接到任何地方的錯誤報告或解釋? –

+0

這篇文章在我的評論中被鏈接,但並沒有那麼出色。這裏是:[http://aspnetwebstack.codeplex.com/workitem/1471](http://aspnetwebstack.codeplex.com/workitem/1471) – emgee

回答

1

您描述的問題是(最近剛剛解決的)ASP.NET WebApi中的一個錯誤。您可以在http://aspnetwebstack.codeplex.com/workitem/1471找到詳細信息。

對於您的字符串屬性,您應該可以使用[必需],但添加參數AllowEmptyStrings = false。我只需要解決方法(如錯誤報告開發人員所述)來處理非字符串屬性。

如果您使用JSON進行反序列化,您可能希望使您的int屬性爲空(int?);沒有使它成爲int? Newtonsoft.Json轉換和空字符串的屬性爲0

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

相關問題