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
Linq Multiple Group by in a List<T> Then Convert to List<T>
Deserialize Json in C# - How to Handle Null Return Values
How to Refresh an Entity Framework Core Dbcontext
Get Properties and Values from Unknown Object
Casting an Object into the Same Type as an Ienumerable Collection
Could Not Start Windows Service, Error 1064
Posting Jsonobject With Httpclient from Web API
C# How to Simply Encrypt a Text File With a Pgp Public Key
Newtonsoft Json Dynamic Property Name
Encode a Filestream to Base64 With C#
How to Get the Currently Loggedin Windows Account from an ASP.NET Page
How to Cast a List into a Type Which Inherits from List<T>
Clearing a Textbox Leaves an Invisible Character
How to Download a File from a Url in C#
C#: How to Force Trailing Zero in Numeric Format String
How to Set Value of Wpf Combobox Item from C# Code