Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 238
biofractal Avatar asked May 09 '12 08:05

biofractal


People also ask

What function is used to determine if a value was sent via query string?

In general you can check the $_GET array to see how many variables have been sent and act accordingly, by using count($_GET) .

How do you pass a string in a query?

To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.

Does query string order matter?

Query string parameters The question mark followed by the parameters and their values is referred to as the “query string.” In the query string, each parameter is listed one right after the other with an ampersand ( & ) separating them. The order of the query string parameters does not matter.

How is a query string generated?

Query strings are also generated by sending a form or by a user typing a query into the address box of the browser. Query strings are contained in request headers. It is wise to not trust the data that is contained in headers, as this information can be falsified by malicious users.


2 Answers

Request.Form.userid.HasValue

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

like image 69
TheCodeJunkie Avatar answered Sep 22 '22 21:09

TheCodeJunkie


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
} 
like image 27
Adeyinka Oluwaseun Doyin Avatar answered Sep 20 '22 21:09

Adeyinka Oluwaseun Doyin