Very simple I'm sure, but driving me up the wall! There is a component that I use in my web application that identifies itself during a web request by adding the header "XYZComponent=true" - the problem I'm having is, how do you check for this in your view?
The following wont work:
if (Request.Headers["XYZComponent"].Count() > 0)
Nor this:
if (Request.Headers.AllKeys.Where(k => k == "XYZComponent").Count() > 0)
Both throw exceptions if the header variable has not been set. Any help would be most appreciated.
Header exists:
or even better:
which will check whether it is set to true. This should be fool-proof because it does not care on leading/trailing whitespace and is case-insensitive (
bool.TryParse
does work onnull
)Addon: You could make this more simple with this extension method which returns a nullable boolean. It should work on both invalid input and null.
Usage (because this is an extension method and not instance method this will not throw an exception on
null
- it may be confusing, though):or
The following code should allow you to check for the existance of the header you're after in
Request.Headers
:... will attempted to count the number of characters in the returned string, but if the header doesn't exist it will return NULL, hence why it's throwing an exception. Your second example effectively does the same thing, it will search through the collection of Headers and return NULL if it doesn't exist, which you then attempt to count the number of characters on:
Use this instead:
Or if you want to treat blank or empty strings as not set then use:
The Null Coalesce operator ?? will return a blank string if the header is null, stopping it throwing a NullReferenceException.
A variation of your second attempt will also work:
Edit: Sorry didn't realise you were explicitly checking for the value true:
Will return false if Header value is false, or if Header has not been set or if Header is any other value other than true or false. Will return true is the Header value is the string 'true'
Firstly you don't do this in your view. You do it in the controller and return a view model to the view so that the view doesn't need to care about custom HTTP headers but just displaying data on the view model: