2014-07-22 31 views
2

我在南希示例應用程序和與請求驗證的問題。Nancy和請求驗證

我使用FluentValidator與BindAndValidate擴展。因此,例如,我有模式:

public class User 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
} 

而且模塊:

Post["/create-user"] = m => this.BindAndValidate<User>()); 

而且有問題的,如果客戶端應用程序調用模塊的參數名稱:「富,年齡:」一些字符串」, 然後南希拋出異常:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Exception: some-string is not a valid value for Int32. ---> System.FormatException: Input string was not in a correct format. 

這裏是通過參數異常任何解決方法(「財產年齡是不是在正確的墊子「)?

感謝

+0

看起來像今天這樣良好記錄在這裏https://github.com/NancyFx/Nancy/wiki/Nancy-and-Validation –

回答

-2

之前綁定你可以嘗試檢查,如果年齡爲int的,如果是則驗證。就像這樣:

int age; 
bool isInt = int.TryParse(Request.Form("Age"), out age); 

if (isInt) 
{ 
    this.BindAndValidate<User>(); 
} 

希望它有幫助。

0

的問題是,綁定失敗,從而驗證從來沒有運行。你可以告訴南希忽略綁定錯誤,但它沒有這樣做優雅(它基本上停在第一個錯誤綁定)。所以然後你的驗證步驟會運行,但可能會抱怨屬性沒有問題,但只是沒有被活頁夾設置。

您可以通過提供自己的BodyDeserializer使用錯誤的Newtonsoft的處理,使裝訂不上發現的第一個錯誤停止得到解決這個問題。見Handle multiple binding errors from ModelBindingException in NancyFX when binding to JSON in Request.Body