2014-07-22 62 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