2

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;

 }
1
  • Show the (sanitized) raw request that works with post man Commented Mar 22, 2017 at 22:35

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.