2

I have sample app in Nancy and have problem with request validation.

I am using FluentValidator with BindAndValidate extension. So for example i have model :

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

And module with :

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

And there is problem, if client app call module with parameters Name:"foo,Age:"some-string", then Nancy throw exception :

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.

Is here any workaround for exception by parameter ("property Age was not in correct format") ?

Thanks

Mennion
  • 2,873
  • 3
  • 20
  • 34

2 Answers2

0

The problem is that the bind fails so the validator never runs. You can tell nancy to ignore binding errors, but it doesn't do so gracefully (it basically stops binding on the first error). So then your validation step does run, but may complain about properties that were ok, but simply were not set by the binder.

You can get around this by providing your own BodyDeserializer that uses Newtonsoft's handling of errors so that the binding doesn't stop on the first error found. See Handle multiple binding errors from ModelBindingException in NancyFX when binding to JSON in Request.Body

Tim
  • 606
  • 4
  • 7
-2

Before binding you could try to check if Age is int, and if it is then to validation. Something like this:

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

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

Hope it helps.

rmares
  • 240
  • 2
  • 7