How to get an specific header value from the HttpResponseMessage

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.


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();
}

If someone like method-based queries then you can try:

    var responseValue = response.Headers.FirstOrDefault(i=>i.Key=="X-BB-SESSION").Value.FirstOrDefault();

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;