get() The get() method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn't exist in the Headers object, it returns null .
The getResponseHeader() method returns the value as a UTF byte sequence. Note: The search for the header name is case-insensitive. If you need to get the raw string of all of the headers, use the getAllResponseHeaders() method, which returns the entire raw header string.
You should be able to use the TryGetValues
method.
HttpHeaders headers = response.Headers;
IEnumerable<string> values;
if (headers.TryGetValues("X-BB-SESSION", out values))
{
string session = values.First();
}
Using Linq aswell, this is how I solved it.
string operationLocation = response.Headers.GetValues("Operation-Location").FirstOrDefault();
I think it's clean and not too long.
Though Sam's answer is correct. It can be somewhat simplified, and avoid the unneeded variable.
IEnumerable<string> values;
string session = string.Empty;
if (response.Headers.TryGetValues("X-BB-SESSION", out values))
{
session = values.FirstOrDefault();
}
Or, using a single statement with a ternary operator (as commented by @SergeySlepov):
string session = response.Headers.TryGetValues("X-BB-SESSION", out var values) ? values.FirstOrDefault() : null;
If someone like method-based queries then you can try:
var responseValue = response.Headers.FirstOrDefault(i=>i.Key=="X-BB-SESSION").Value.FirstOrDefault();
You are trying to enumerate one header (CacheControl) instead of all the headers, which is strange. To see all the headers, use
foreach (var value in responseHeadersCollection)
{
Debug.WriteLine("CacheControl {0}={1}", value.Name, value.Value);
}
to get one specific header, convert the Headers to a dictionary and then get then one you want
Debug.WriteLine(response.Headers.ToDictionary(l=>l.Key,k=>k.Value)["X-BB-SESSION"]);
This will throw an exception if the header is not in the dictionary so you better check it using ContainsKey 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