简体   繁体   English

将HttpClient转换为RestSharp

[英]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. 我有Httpclient函数,我试图将其转换为RestSharp,但是我遇到了使用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: 这段代码在我的HttpClient代码中,效果很好,但是我无法在RestSharp中使用它,在使用RestSharp时,我总是会得到未授权,如下所示:

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? 我是否缺少身份验证功能?

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 在Fiddler嗅探之后,我得出的结论是RestSharp将access_token作为Basic发送,因此使用普通参数而不是HttpBasicAuthenticator可以强制使用Bearer前缀的令牌

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

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: 如果有人发生这种情况,从V 106.6.10开始,您可以简单地向客户端添加默认参数,以免于不得不将Auth令牌添加到每个请求方法中:

private void InitializeClient()
{
     _client = new RestClient(BASE_URL);           
     _client.DefaultParameters.Add(new Parameter("Authorization",
                string.Format("Bearer " + TOKEN), 
                ParameterType.HttpHeader));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM