Converting HttpClient to RestSharp

2020-07-06 02:17发布

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?

3条回答
Viruses.
2楼-- · 2020-07-06 02:48

Try this

 RestClient client = new RestClient("http://place.holder.nl");
 RestRequest request = new RestRequest("api/personeel/myID",Method.Get);
 request.AddParameter("Authorization",$"Bearer {access_token}",ParameterType.HttpHeader);
 request.AddHeader("Accept", "application/json");
 request.RequestFormat = DataFormat.Json;
 var response = client.Execute(request);
查看更多
Summer. ? 凉城
3楼-- · 2020-07-06 03:00

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

查看更多
Evening l夕情丶
4楼-- · 2020-07-06 03:00

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));
}
查看更多
登录 后发表回答