1

I'm trying GET/POST call API, I've tried this and it works but I can't use RestSharp because it is not compatible with the rest of the application. Is there another way I can use a bearer token?

PS. The Token will never expire so I can pass it as a fixed string.

using System;
using RestSharp;
namespace HelloWorldApplication {
  class HelloWorld {
    static void Main(string[] args) {
      var client = new RestClient("https://test.com/api/");
      client.Timeout = -1;
      var request = new RestRequest(Method.GET);
      request.AddHeader("Authorization", "Bearer myToken");
      IRestResponse response = client.Execute(request);
      Console.WriteLine(response.Content);
    }
  }
}

I've tried to use HttpClient too

 static async Task Main(string[] args)
 {  
            var endpoint = new Uri("https://test.com/api/'");

            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "myToken");
            var result = httpClient.GetAsync(endpoint).Result;
            var json = result.Content.ReadAsStringAsync().Result;
            Console.WriteLine(json);
}
  • 1
    What client are you allowed to use? Is this a duplicate of: https://stackoverflow.com/questions/14627399/setting-authorization-header-of-httpclient ? – Steve V Nov 07 '22 at 20:01
  • My Application is a Web Form Application @SteveV. I have seen and tried the solutions on the page you linked, but none of them worked, basically because I don't need a username and password to authenticate. All I need is the Token string. – User_789465 Nov 07 '22 at 20:15
  • Just use HttpClient class instead of RestClient. If the c# version is too old, use WebClient. – GH DevOps Nov 07 '22 at 20:39
  • First, use `await httpClient.GetAsync(endpoint) ...` instead of `.Result;` Same goes for `result.Content.ReadAsStringAsync()`. The HttpClient code should work, what is not working for you? – L01NL Nov 08 '22 at 08:09

0 Answers0