Interesting QueryString parameter behavior in ASP.NET

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:

    [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]}

    [0]: "b"
    [1]: null
    [2]: "e"


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:


and indeed:

    [a] => b
    [c] => 
    [d] => e

So, keep that in mind when using empty query string params.

This entry was posted in .NET and tagged , . Bookmark the permalink.