Marshall Marshall - 8 hours ago 2
C# Question

How to pass header values in web api using HttpClient

I'm new to ASP.NET Web API 2. I'm trying to access a third party API, so to access it first I need to pass a authorization Token in the header with the API URL. I'm able to access the data with Postman but I'm unable to do it with Code.

Following is my code, I'm not sure if I'm going in the right direction. Any help would be appreciated.

using (var client = new HttpClient())
{
client.BaseAddress = new Uri("Url");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new HttpContext.Current.Request.Headers.Add("Authorization", "Token "+ "MyToken");
var re = Request;
var headers = re.Headers;

if (headers.Contains("Token"))
{
string token = headers.GetValues("Token").First();
}

return null;

}

Answer

If setting the default authorization header of the HttpClient for all its requests use a AuthenticationHeaderValue set on the client.DefaultRequestHeaders.Authorization

like in the following example...

//...other code removed for brevity

var tokenType = "Token"; //Other APIs use Bearer or other auth types.
var token = "MyToken";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, token);

//...other code removed for brevity.

Any requests made using the client will have an authorization header

Authorization Token MyToken