Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an specific header value from the HttpResponseMessage

People also ask

How do I find a header value?

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 .

How do I use getResponseHeader?

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