I recently ran into some strange behavior in ASP.NET when browsing to the error-log of my current project. Somebody was passing in some invalid query string parameters. That shouldn’t be a problem, but for some reason the error log contained some null-reference exceptions.
The query string was something along the lines of ?a=b&c&d=e. Notice the ‘c’ parameter isn’t in key=value format.
The culprit was the following piece of code:
var keysWithStuff = Request.QueryString.AllKeys.Where(x => x.Contains("stuff"));
but why?
Well, upon debugging I learned ASP.NET interprets the query string the following way:
Request.QueryString
{a=b&c&d=e}
[System.Web.HttpValueCollection]: {a=b&c&d=e}
base {System.Collections.Specialized.NameObjectCollectionBase}: {a=b&c&d=e}
_all: null
_allKeys: {string[3]}
AllKeys: {string[3]}
Request.QueryString.AllKeys
{string[3]}
[0]: "b"
[1]: null
[2]: "e"
Request.QueryString[1]
"c"
This came as a surprise because I distinctly remembered those query-string parameters being treated as keys in PHP; so I more or less assumed that’s how they were supposed to work.
I double-checked with a quick PHP script:
print_r($_REQUEST);
and indeed:
Array
(
[a] => b
[c] =>
[d] => e
)
So, keep that in mind when using empty query string params.