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

2

7

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

Wondawonder answered 9/5, 2012 at 8:50 Comment(0)
T
14
Request.Form.userid.HasValue

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

Trisaccharide answered 9/5, 2012 at 9:18 Comment(0)
L
2

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
} 
Latoya answered 13/7, 2012 at 23:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.