How do you test your Request.QueryString[] variables?
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?
Below is an extension method that will allow you to write code like this:
int id = request.QueryString.GetValue<int>("id");
DateTime date = request.QueryString.GetValue<DateTime>("date");
It makes use of TypeDescriptor
to perform the conversion. Based on your needs, you could add an overload which takes a default value instead of throwing an exception:
public static T GetValue<T>(this NameValueCollection collection, string key)
{
if(collection == null)
{
throw new ArgumentNullException("collection");
}
var value = collection[key];
if(value == null)
{
throw new ArgumentOutOfRangeException("key");
}
var converter = TypeDescriptor.GetConverter(typeof(T));
if(!converter.CanConvertFrom(typeof(string)))
{
throw new ArgumentException(String.Format("Cannot convert '{0}' to {1}", value, typeof(T)));
}
return (T) converter.ConvertFrom(value);
}
Use int.TryParse instead to get rid of the try-catch block:
if (!int.TryParse(Request.QueryString["id"], out id))
{
// error case
}
Try this dude...
List<string> keys = new List<string>(Request.QueryString.AllKeys);
Then you will be able to search the guy for a string real easy via...
keys.Contains("someKey")
I'm using a little helper method:
public static int QueryString(string paramName, int defaultValue)
{
int value;
if (!int.TryParse(Request.QueryString[paramName], out value))
return defaultValue;
return value;
}
This method allows me to read values from the query string in the following way:
int id = QueryString("id", 0);