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


No Comments