C# ASP.NET QueryString parser C# ASP.NET QueryString parser asp.net asp.net

C# ASP.NET QueryString parser


A simple way to parse (if you dont want to do type conversions) is

 HttpUtility.ParseQueryString(queryString);

You can extract querystring from a URL with

 new Uri(url).Query


Given that you only handle three different types, I would suggest three different methods instead - generic methods are best when they work well with every type argument which is permitted by the type constraints.

In addition, I would strongly recommend that for int and DateTime you specify the culture to use - it shouldn't really depend on the culture the server happens to be in. (If you have code to guess the culture of the user, you could use that instead.) Finally, I'd also suggest supporting a well-specified set of DateTime formats rather than just whatever TryParse supports by default. (I pretty much always use ParseExact/TryParseExact instead of Parse/TryParse.)

Note that the string version doesn't really need to do anything, given that value is already a string (although your current code converts "" to null, which may or may not be what you want).


I've written the following method to parse the QueryString to strongly typed values:

public static bool TryGetValue<T>(string key, out T value, IFormatProvider provider){    string queryStringValue = HttpContext.Current.Request.QueryString[key];    if (queryStringValue != null)    {        // Value is found, try to change the type        try        {            value = (T)Convert.ChangeType(queryStringValue, typeof(T), provider);            return true;        }        catch        {            // Type could not be changed        }    }    // Value is not found, return default    value = default(T);    return false;}

Usage example:

int productId = 0;bool success = TryGetValue<int>("ProductId", out productId, CultureInfo.CurrentCulture);

For a querystring of ?productId=5 the bool would be true and int productId would equal 5.

For a querystring of ?productId=hello the bool would be false and int productId would equal 0.

For a querystring of ?noProductId=notIncluded the bool would be false and int productId would equal 0.