Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 370
Neo Avatar asked Feb 17 '16 09:02

Neo


2 Answers

You can check for null like so:

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

Tried and tested

like image 92
Oluwafemi Avatar answered Oct 29 '22 17:10

Oluwafemi


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();
}
like image 33
Dai Avatar answered Oct 29 '22 15:10

Dai