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?
You can check for null like so:
if(System.Web.HttpContext.Current.Request.Headers["MyCustomerId"] != null)
{
// do something
}
Tried and tested
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With