How to Get an Specific Header Value from the Httpresponsemessage

How to get an specific header value from the HttpResponseMessage

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 RestSharp to get header value from HttpResponseMessage in web API?

So I should have specified that this was a .NET Core application. To fix the problem, I had to go to the Startup.cs file and add the following to the ConfigureServices method:

Change services.AddMvc(); to services.AddMvc().AddWebApiConventions();

You will need the NuGet package Microsoft.AspNetCore.Mvc.WebApiCompatShim, which allows compatibility with the old Web Api 2 way.

HttpClient retrieve all headers

Well, HttpResponseMessage.Headers returns an HttpResponseHeaders reference, so you should be able to use GetValues()

string error = response.Headers.GetValues("X-Error").FirstOrDefault();
string errorCode = response.Headers.GetValues("X-Error-Code").FirstOrDefault();

How to read header data from a web API response in .NET Core?

I found the solution:

var headers = response.Headers;
string role = "";
if (headers.TryGetValues("Role", out IEnumerable<string> headerValues))
role = headerValues.FirstOrDefault();

Don't forget to add a reference to System.Linq.

Related Topics

Leave a reply