【问题标题】:Nancy and request validation南希和请求验证
【发布时间】:2014-09-13 18:16:53
【问题描述】:

我在 Nancy 有示例应用,但请求验证有问题。

我正在使用带有 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"的模块, 然后南希抛出异常:

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.

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

谢谢

【问题讨论】:

标签: model-binding nancy request-validation


【解决方案1】:

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

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

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

希望对你有帮助。

【讨论】:

    【解决方案2】:

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

    您可以通过提供自己的 BodyDeserializer 来解决此问题,该程序使用 Newtonsoft 的错误处理,以便绑定不会在发现第一个错误时停止。见Handle multiple binding errors from ModelBindingException in NancyFX when binding to JSON in Request.Body

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 2016-09-20
      • 2015-06-09
      • 1970-01-01
      相关资源
      最近更新 更多