Reputation: 67
I am trying to do a GET call using HttpClient with Authorization header. [Authorization: Bearer ].
The HttpClient.GetAsync always returns 401 (unauthorized). When the same call is made using .netstarndard's HttpClient it works fine. Below is the code which shows me 401. The same endpoint works in Postman as well. Please help me on what i am missing.
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("GET"), "<Get endpoint>");
request.Headers.Add("Authorization", "Bearer " + "<token>");
var resp = client.SendAsync(request).Result;
I also tried with the below code as well, which is also not working.
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "<token>");
client.GetAsync("<get endpoint>");
And with this.
HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");
Note: The .netstandard HttpClient works with the same code. Problem is only with .NET Framework. [Please don't suggest me to use .netstarndard library as I want to call the HttpClient Get from my .NET Framework application.]
I am trying to call OAuth's identity/connect/userinfo endpoint. Don't know if it makes any difference.
Please help. Thanks in Advance, Kannan
Upvotes: 0
Views: 2589
Reputation:
I will recommend you to use Http Client Wrapper as shown below in the url. There are example methods which you can use.
https://github.com/elgunmirze/HttpClientWrapper
Upvotes: -1
Reputation: 53
You said you tried
HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", "<token>"); client.GetAsync("<get endpoint>");
Here you pass "Authorization" to the AuthenticationHeaderValue
, which I think is mistake.
You should pass the scheme to AuthenticationHeaderValue
not the header name.So "Bearer" in your case.
Try this
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "<token>");
client.GetAsync("<get endpoint>");
Upvotes: 0
Reputation: 7049
Try this way:
HttpClient client = new HttpClient();
var requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://your.site.com");
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", your_token);
client.SendAsync(requestMessage);
Upvotes: 2