Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting HttpClient to RestSharp

I have Httpclient functions that I am trying to convert to RestSharp but I am facing a problem I can't solve with using google.

client.BaseAddress = new Uri("http://place.holder.nl/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",access_token);
HttpResponseMessage response = await client.GetAsync("api/personeel/myID");
string resultJson = response.Content.ReadAsStringAsync().Result;

This Code is in my HttpClient code, which works good, but I can't get it to work in RestSharp, I always get Unauthorized when using RestSharp like this:

RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest();
client.Authenticator = new HttpBasicAuthenticator("Bearer", access_token);
request.AddHeader("Accept", "application/json");
request.Resource = "api/personeel/myID";
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);

Am I missing something with authenticating?

like image 748
Maarten Avatar asked Mar 17 '16 13:03

Maarten


People also ask

Does RestSharp use HttpClient?

Since RestSharp uses the HttpClient, we should consider similar issues regarding the RestClient instantiation.

Should I use HttpClient or RestSharp?

Some prefer to use HttpClient because it is already built into the framework. So there's no need to add extra bloat to your project. RestSharp, like any library, is easier to use because someone already did the hard work and ironed out the problems gotten along the way.

What is RestSharp?

RestSharp is a C# library used to build and send API requests, and interpret the responses. It is used as part of the C#Bot API testing framework to build the requests, send them to the server, and interpret the responses so assertions can be made.


2 Answers

This has fixed my problem:

RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest("api/personeel/myID", Method.GET);
request.AddParameter("Authorization", 
string.Format("Bearer " + access_token),
            ParameterType.HttpHeader);
var response = client.Execute(request);

Upon sniffing with Fiddler, i came to the conclusion that RestSharp sends the access_token as Basic, so with a plain Parameter instead of a HttpBasicAuthenticator i could force the token with a Bearer prefix

like image 94
Maarten Avatar answered Oct 27 '22 13:10

Maarten


If anyone happens on this, it looks like as of V 106.6.10 you can simply add default parameters to the client to save yourself from having to add your Auth token to every request method:

private void InitializeClient()
{
     _client = new RestClient(BASE_URL);           
     _client.DefaultParameters.Add(new Parameter("Authorization",
                string.Format("Bearer " + TOKEN), 
                ParameterType.HttpHeader));
}
like image 44
user12097461 Avatar answered Oct 27 '22 11:10

user12097461