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