Search code examples
c#asp.net-web-apixamarinrestsharp

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?


Solution

  • 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