Monday, August 30, 2010

In what order does HttpRequest go through the collections?

I found this question on the ASP.NET forums. The member asking this question already knew that the collections were Cookies, Form, Servervariables and Querystring but wanted to know the exact order. Well I got curious but instead of making a dedicated test project I opened up Reflector. Looking up the HttpRequest class' indexer gave me this code:
public string this[string key] {     get     {         string str = this.QueryString[key];         if (str != null)         {             return str;         }         str = this.Form[key];         if (str != null)         {             return str;         }         HttpCookie cookie = this.Cookies[key];         if (cookie != null)         {             return cookie.Value;         }         str = this.ServerVariables[key];         if (str != null)         {             return str;         }         return null;     } }
It's on the other hand always better to directly call the most specific collection directly. This avoids getting strange things in your code like expecting a key in the Form collection and getting the same key from the QueryString collection which could have a different, or none at all, value than what you expect. Fun debugging sessions follow after that…

No comments: