HttpRequest QueryValue extension methods

Getting non string values from the querystring can be a chore if you need to read alot of values; parsing to the required type and ensuring the querystring value doesn’t cause an exception ("adsf" cannot become an integer) can add alot of code to each page. So a long while ago I created a small helper class to do this for me, which I’ve now upgraded (after reading a blog entry by ScottH about TypeConverters) to use generics and extension methods. I’ve also included methods to get a value from the Request.Form property.

using System;
using System.Web;
using System.ComponentModel;

namespace LukeSmith.Web
{
    public static class HttpRequestHelper
    {
        public static T? GetQueryValue<T>(this HttpRequest request, string name)
            where T : struct
        {
            return ConvertFromString<T>(request.QueryString[name]);
        }

        public static T? GetQueryValue<T>(this HttpRequest request, int index)
            where T : struct
        {
            return ConvertFromString<T>(request.QueryString[index]);
        }

        public static T? GetFormValue<T>(this HttpRequest request, string name)
            where T : struct
        {
            return ConvertFromString<T>(request.Form[name]);
        }

        public static T? GetFormValue<T>(this HttpRequest request, int index)
            where T : struct
        {
            return ConvertFromString<T>(request.Form[index]);
        }

        private static T? ConvertFromString<T>(string value)
            where T : struct
        {
            T? result = null;

            if (!string.IsNullOrEmpty(value))
            {
                TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));

                if (converter.CanConvertFrom(typeof(string)))
                {
                    try
                    {
                        object obj = converter.ConvertFromInvariantString(value);
                        result = (T)obj;
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            return result;
        }
    }
}

Updated: Why Try/Catch was used

2 Responses to “HttpRequest QueryValue extension methods”

  1. Dale Says:

    Nice idea but coding by error (try/catch to catch expected errors) is a bad idea. If the error is expected, such as ‘asdf’ converting to an int, use int.TryParse and skip the creation of the exception. Generating the exception can take several seconds in .Net. Trying this for several entries in a query string could be a serious performance hit.

  2. Luke Smith Says:

    I have never come across exceptions taking several seconds to generate, do you have a source for this claim?

    I’ve made my comment to using try/catch in a new post
    http://blog.lukesmith.net/index.php/2008/07/31/sometimes-you-have-to-catch-an-exception/

Leave a Reply