Working with query strings

by Mads Kristensen 27. January 2007 20:52

In many cases we write our ASP.NET logic around query strings in order to show the right product page or what not. The first thing we do is to check if the query string exists in the first place before we start using it. It could look like this:

if (Request.QueryString["id"] != null)

{

  // Do something with the querystring

}

The only problem with the above check to see if the query string is null, is that we don’t take into consideration if the query string is filled or not. That could lead to unhandled exceptions in the code. Instead we should check for query strings like this:

if (!String.IsNullOrEmpty(Request.QueryString["id"]))

{

  // Do something with the querystring

}

Then there is the data type of the query string. Our code might need an integer of 5 digits to get the right information from the database, so if we pass it a string we could end up with a data type mismatch exception. So we do the check again more thoroughly:

if (!String.IsNullOrEmpty(Request.QueryString["id"]) && Request.QueryString["id"].Length == 5)

{

  // Do something with the querystring

}

Now we know that we get a query string suitable for further processing. You can then do more precise data type checks using the TryParse method of most value types or by some other logic.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

ASP.NET

Comments

1/28/2007 10:21:44 AM #

 Eber Irigoyen

it helps, but is still very error prone, I prefer the use of a proxy class (maybe even using an enumeration instead of hardcoded strings) that gives me type safety and takes care of all the checking for me

Eber Irigoyen |

1/28/2007 4:11:03 PM #

Mads Kristensen

If you use a proxy class you still need to parse the query strings.

Mads Kristensen |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008