2011-07-22

Safely Retrieving Values in ASP.Net 4.0

This is a C# 4.0 updated version of Safely Retrieving Values in ASP.Net 2.0 from January, 2009.
Not everything we do in ASP.Net gets sent via web form.  We still do a lot involving Request.QueryString[] and Request.Form[]. The trick is dealing with input that may or may not be there or may even be in the wrong format (such as someone tweaking the URL to see if they can break your site or insert content for a cross-site scripting attack).
Let's say we need an integer passed in...
int mySelfDocumentingVariableName = Request.QueryString["xyz"] as int? ?? 0;
This will attempt to read in whatever xyz equals in the URL and convert it to a nullable int. We don't want a bunch of null checks throughout our code though, so we null coalesce the value to 0 if it wasn't in the URL or wasn't a valid integer. If zero is a meaningful value, you could define the variable as an int? (nullable int) or use another value, such as -1, int.MinValue, or int.MaxValue to indicate no proper value was provided.

If you'd like greater control over the order in which the Request[] array is used to find a value, perhaps to prevent a QueryString value taking precedence over a Form value. Rather than write checks on a Request.Form for a key and then a Request.QueryString, you could do the following...
double someDoubleINeed = Request.Form["amt"] as double? ?? Request.QueryString["amt"] as double? ?? 0D;
Strings are fairly straightforward since they're already nullable. If you want to avoid null reference exceptions, the following is my means of doing so (relatively unchanged from the ASP.Net 2.0 method, just not written as a function)...
string aStringIWant = Request.QueryString["abc"] as string ?? string.Empty;