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
In general you can check the $_GET array to see how many variables have been sent and act accordingly, by using count($_GET) .
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.
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.
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.
Request.Form.userid.HasValue
Works for all DynamicDictionary members, such as Form, Query and route parameters
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With