Converting HttpClient to RestSharp

为君一笑 提交于 2019-12-06 00:02:14

问题


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?


回答1:


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




回答2:


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);



回答3:


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));
}


来源:https://stackoverflow.com/questions/36061745/converting-httpclient-to-restsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!