2

我在南希有示例应用程序,但请求验证有问题。

我正在使用带有 BindAndValidate 扩展的 FluentValidator。所以例如我有模型:

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

和模块:

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

还有一个问题,如果客户端应用程序调用带有参数 Name:"foo, Age:"some-string" 的模块,那么 Nancy 会抛出异常:

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.

这里是否有任何参数异常的解决方法(“属性年龄的格式不正确”)?

谢谢

4

2 回答 2

0

问题是绑定失败,所以验证器永远不会运行。您可以告诉 nancy 忽略绑定错误,但它不会优雅地这样做(它基本上会在第一个错误时停止绑定)。因此,您的验证步骤确实运行了,但可能会抱怨属性没问题,但只是没有由活页夹设置。

您可以通过提供自己的 BodyDeserializer 来解决此问题,该程序使用 Newtonsoft 的错误处理,以便绑定不会在发现第一个错误时停止。请参阅在 Request.Body 中绑定到 JSON 时处理来自 NancyFX 中的 ModelBindingException 的多个绑定错误

于 2018-02-16T18:34:16.837 回答
-2

在绑定之前,您可以尝试检查 Age 是否为 int,如果是则进行验证。像这样的东西:

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

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

希望能帮助到你。

于 2014-07-23T18:57:55.130 回答