我在Nancy有一个示例应用程序,并且在请求验证方面存在问题。
我正在使用带有BindAndValidate扩展名的FluentValidator。所以例如我有模特:
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
和模块:
Post["/create-user"] = m => this.BindAndValidate<User>());
还有问题,如果客户端应用程序调用模块带参数名称:“foo,年龄:”some-string“, 然后南希抛出异常:
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 :(得分:0)
问题是绑定失败,因此验证程序永远不会运行。您可以告诉nancy忽略绑定错误,但它没有优雅地执行此操作(它基本上会停止对第一个错误的绑定)。那么你的验证步骤确实会运行,但可能会抱怨属性没问题,但只是没有被绑定器设置。
你可以通过提供自己的BodyDeserializer来解决这个问题,它使用Newtonsoft处理错误,这样绑定就不会在找到的第一个错误上停止。见Handle multiple binding errors from ModelBindingException in NancyFX when binding to JSON in Request.Body
答案 1 :(得分:-2)
在绑定之前,您可以尝试检查Age是否为int,然后是否为验证。像这样:
int age;
bool isInt = int.TryParse(Request.Form("Age"), out age);
if (isInt)
{
this.BindAndValidate<User>();
}
希望它有所帮助。