Search code examples
c#coding-styletryparseisnumericrequest.querystring

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?


Solution

  • 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);
    }