我有尝试转换为RestSharp的Httpclient函数,但遇到了使用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;
这段代码在我的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);
我是否缺少身份验证功能?
最佳答案
这解决了我的问题:
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);
在Fiddler嗅探之后,我得出的结论是RestSharp将access_token发送为Basic,因此使用普通参数而不是HttpBasicAuthenticator可以强制使用Bearer前缀的 token
关于c# - 将HttpClient转换为RestSharp,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36061745/