NancyFX: How do I check if query-string / form values have been correctly passed to my handler?

StackOverflow https://stackoverflow.com/questions/10512727

  •  06-06-2021
  •  | 
  •  

Question

Nancy passes my query-string and form values to my handlers via a dynamic variable. The example below shows form values being passed in to a POST handler via the Nancy request e.g. Request.Form.xxx.

Handler

Post["/"] = _ =>
    {
        var userId = (string) Request.Form.userid;
        if (userId.IsEmpty()) return HttpStatusCode.UnprocessableEntity;
        return HttpStatusCode.OK;
    };

You can see that I am casting the userid to a string and then using a string extension method to check if the value is null or empty string (equivalent to string.IsNullOrEmpty()).

What I would prefer is to to have the extension method on the dynamic type so I could perform my sanity checks before doing anything else. I want code like this:

if(Request.Form.userid.IsEmpty()) return HttpStatusCode.UnprocessableEntity;

However, you cannot have extension methods for dynamic types. Also, you cannot check for the presence of a property via reflection. Welcome to the DLR.

Question

What is the easiest, safest way to perform pre-checks to ensure that the expected query/form values have been passed to my Nancy handler?

Thanks

Was it helpful?

Solution

Request.Form.userid.HasValue

Works for all DynamicDictionary members, such as Form, Query and route parameters

OTHER TIPS

You can use Bind i.e a ModelBinder to Bind your model to the form, where the properties of the model class corresponds to your HTML control names.

var course = this.Bind<Course>(); // Course is our model class 
if(course != null) {
    // your codes go here
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top