Getting a type value from the Request object

A little bit of boiler-plate code I've used in the past for retrieving a value from the asp.net Request object (when working with webform back in the day!) is:

/// <summary>
/// Retrieve a value from the Request
/// </summary>
/// <typeparam name="T">The type to coerce the value to</typeparam>
/// <param name="value">The HttpRequest to extract the value from</param>
/// <param name="key">The value to search for</param>
/// <param name="defaultValue">The value to provide if it's not found</param>
public static T GetRequestValue<T>(this HttpRequest value, string key, T defaultValue)
{
    var returnValue = defaultValue;
    try
    {
        Type typeOfT = typeof(T);
        if ((value.Params.AllKeys.Contains(key)) && (!string.IsNullOrEmpty(value.Params[key])))
        {
            var requestValue = value.Params[key];
            if ((typeOfT.IsGenericType) && (typeOfT.GetGenericTypeDefinition().Equals(typeof(Nullable<>))))
            {
                returnValue = (T)ChangeType<T>(requestValue);
            }
            else
            {
                returnValue = (T)Convert.ChangeType(requestValue, typeof(T));
            }
        }
    }
    catch
    {
        // Logging / Diagnostics specific to the app go here!
    }
    return returnValue;
}
/// <summary>
/// Convert a value of one type to another
/// </summary>
/// <typeparam name="T">The target type</typeparam>
/// <param name="value">The value to convert</param>
/// <returns>The specified value as the specified type</returns>
public static T ChangeType<T>(object value)
{
    Type conversionType = typeof(T);
    if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
       if (value == null)
        {
            return default(T);
        }         else
        {
            NullableConverter nullableConverter = new NullableConverter(conversionType);
            conversionType = nullableConverter.UnderlyingType;
        }
     }
     return (T)Convert.ChangeType(value, conversionType);
}

An example of calling it would be (assuming that the class that defines the extention method has been pulled into scope):

var numericValue = Request.GetRequestValue<int>("RequestFieldToAccess", -1);

In the example above, if the request didn't contain anything called "RequestFieldToAccess", the variable numericValue will be set to -1

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment