I'm making an HTTP call. My response contains a session code X-BB-SESSION
in the header section of the HttpResponseMessage
object. How do I get that specific header value?
I am using a foreach statement to iterate through all the headers (MSDN link). However the compiler keeps saying that it cannot be done:
foreach statement cannot operate on variables of type
System.net.http.headers.cachecontrolheadervalue because
'System.net.http.headers.cachecontrolheadervalue' doesn't contain
a public definition for 'GetEnumerator'
This is the code I'm trying:
//Connection code to BaasBox
HttpResponseMessage response = await client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead);
if (response.IsSuccessStatusCode)
{
//get the headers
HttpResponseHeaders responseHeadersCollection = response.Headers;
foreach (var value in responseHeadersCollection.CacheControl) --> HERE
{
string sTemp = String.Format("CacheControl {0}={1}", value.Name, value.Value);
} else
{
Console.WriteLine("X-BB-SESSION: NOT Found");
}
The header content from where I'm trying to get the value (X-BB-SESSION
value) is something like:
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Requested-With
X-BB-SESSION: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
You are trying to enumerate one header (CacheControl) instead of all the headers, which is strange. To see all the headers, use
to get one specific header, convert the Headers to a dictionary and then get then one you want
This will throw an exception if the header is not in the dictionary so you better check it using ContainsKey first
Though Sam's answer is correct. It can be somewhat simplified, and avoid the unneeded variable.
If someone like method-based queries then you can try:
Using Linq aswell, this is how I solved it.
I think it's clean and not too long.
You should be able to use the
TryGetValues
method.