Neo
Neo

Reputation: 16239

Unable to check null for header value in request

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?

Upvotes: 6

Views: 12084

Answers (3)

Jpsy
Jpsy

Reputation: 20892

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

Upvotes: 3

Oluwafemi
Oluwafemi

Reputation: 14899

You can check for null like so:

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

Tried and tested

Upvotes: 5

Dai
Dai

Reputation: 155608

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();
}

Upvotes: 4

Related Questions