ServerVariables empty unless Debug

Just had a really strange issue where I'm trying to log some ServerVariables when an error occurs.

The bug was when I ran the code without debugging, no ServerVariables were being logged.
If I went into Debug, and hovered my mouse over the ServerVariables variable, it had all the information I was looking for.
After that, it logged everything fine.

It seems called a Get on the ServerVariables variable was causing it to initialize properly.

After some further investigation, I found out I was relying on the NameValueCollection.HasKeys() method to see if I had any value.
This returns false. Just by calling Request.ServerVariables.Count, this completely fixes the problem.

So I changed the code as follows, and everything worked as expected

Changed From:

NameValueCollection nvc = Request.ServerVariables;

if(nvc == null) return;
if (nvc.HasKeys())
  //Get ServerVariables Information

Changed To:

NameValueCollection nvc = Request.ServerVariables;

if(nvc == null || nvc.Count == 0) return;
if (nvc.HasKeys())
  //Get ServerVariables Informatione

posted @ Wednesday, September 03, 2008 7:46 AM