'NullReferenceException retrieving non-null header values for custom headers

I'm trying to retrieve custom header values. I only need the first value, and the values are non-null, confirmed by dumping all the header keys & values to text file.

I have two methods, and I don't understand why the one always gives a NullReferenceException and the other returns the value properly. This only happens for custom headers - standard headers (like 'Content-Type') it works fine.

Obviously I can use the method that works, but I usually use this "in-line", not in a function, and the second method is simpler to use that way. Also, I'd really like to understand what's causing the exception - to my untrained eyes there's not much difference. (I know the first checks the value array's length, but the second method gives NullReferenceException even when there is a value.)

Written as functions, these are the two methods:

// This works properly for all keys
private String getHeaderValue(HttpContext context, string key) {
   String ret = String.Empty;

   if (context.Request.Headers.AllKeys.Contains(key))
   {
      String[] vals = context.Request.Headers.GetValues(key);
      if (vals.Length > 0) {
         ret = vals[0];
      }
   }
   return ret;
 }

// This always gives NullReferenceException for custom keys
private String getHeaderValueException(HttpContext context, string key)
{
   String ret = String.Empty;
   if (context.Request.Headers.AllKeys.Contains(key))
   {
      ret = context.Request.Headers.GetValues(key)[0]; // NullReferenceException
   }
   return ret;
}

I would greatly appreciate anyone who can help me understand.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source