6

I tried to get header value like below -

IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomerId");
var id = headerValues.FirstOrDefault();

If header value is null or not present it is throwing error - InvalidOperationException

The null check for GetValues doesn't serve any value as it will never return null. If the header doesn't exist you will get an InvalidOperationException

Any trick to do so?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Neo
  • 15,491
  • 59
  • 215
  • 405

3 Answers3

5

You can check for null like so:

 if(System.Web.HttpContext.Current.Request.Headers["MyCustomerId"] != null)
   {
      // do something
   }

Tried and tested

Oluwafemi
  • 14,243
  • 11
  • 43
  • 59
4

request.Headers is an instance of System.Net.Http.HttpHeaders (via the HttpRequestHeaders subclass). It has a method TryGetValues which can be used to safely retrieve the values of a header.

String header = null;
IEnumerable<String> headerValues;
if( this.Request.Headers.TryGetValues("HeaderName", out headerValues) ) {
    header = headerValues.First();
}
Dai
  • 141,631
  • 28
  • 261
  • 374
3

You can use Headers.Contains() to test the existence of any headers.
See examples in this answer.

Jpsy
  • 20,077
  • 7
  • 118
  • 115