ASP.NET QueryString Parse Gotcha

There are times when it’s useful to throw a token parameter on a URL and have the receiving page test for the existence of the parameter. For example:

/website/page.aspx?foo

What’s significant is whether the token exists or not. It doesn’t need to have a value.

When I tried to use this trick in an ASP.NET 2.0 based application I found an issue. I expected to be able to test something like:

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

Parameters have the form <name>=<value> and I expected “foo” to be taken as a name with no value. But “foo” wasn’t a key in the QueryString collection. “foo” was interpreted as a value and the key was null.

That’s not very useful.

And I don’t recall any other web development environment behaving that way. I quickly tested against JSP and ‘classic’ ASP. Sure enough. In JSP/ASP “foo” is interpreted as a name with a null or empty value.

So how to test for “foo” in ASP.NET? I didn’t want to iterate the whole QueryString collection. That would be wasteful. I didn’t want to depend on an index position. Depending on fixed positions is brittle and counter to the whole point of using name/value pairs.

My solution? I changed my URL to

/website/page.aspx?foo=