Reputation: 16219
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: 12073
Reputation: 20852
You can use Headers.Contains()
to test the existence of any headers.
See examples in this answer.
Upvotes: 3
Reputation: 14879
You can check for null like so:
if(System.Web.HttpContext.Current.Request.Headers["MyCustomerId"] != null)
{
// do something
}
Tried and tested
Upvotes: 5
Reputation: 155025
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