I frequently make use of Request.QueryString[]
variables.
In my Page_load
I often do things like:
int id = -1;
if (Request.QueryString["id"] != null) {
try
{
id = int.Parse(Request.QueryString["id"]);
}
catch
{
// deal with it
}
}
DoSomethingSpectacularNow(id);
It all seems a bit clunky and rubbish. How do you deal with your Request.QueryString[]
s?
Well for one thing use int.TryParse instead...
That assumes that "not present" should have the same result as "not an integer" of course.
EDIT: In other cases, when you're going to use request parameters as strings anyway, I think it's definitely a good idea to validate that they're present.
I modified Bryan Watts' answer so that if the param your asking does not exist and you have specified a nullable type it will return null :
You can now do this :
I actually have a utility class that uses Generics to "wrap" session, which does all of the "grunt work" for me, I also have something almost identical for working with QueryString values.
This helps remove the code dupe for the (often numerous) checks..
For example:
NOTE:
This obviously makes use of statics, which some people don't like because of the way it can impact test code.. You can easily refactor into something that works based on instances and any interfaces you require.. I just think the statics example is the lightest.
Hope this helps/gives food for thought.
I'm using a little helper method:
This method allows me to read values from the query string in the following way:
Eeee this is a karma risk...
I have a DRY unit-testable abstraction because, well, because there were too many querystring variables to keep on in a legacy conversion.
The code below is from a utility class whose constructor requires a NameValueCollection input (this.source) and the string array "keys" is because the legacy app was rather organic and had developed the possibility for several different strings to be a potential input key. However I kind of like the extensibility. This method inspects the collection for the key and returns it in the datatype required.