【问题标题】:Converting HttpClient to RestSharp将 HttpClient 转换为 RestSharp
【发布时间】:2016-03-17 13:19:04
【问题描述】:

我有 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;

此代码在我的 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);

我在身份验证方面遗漏了什么吗?

【问题讨论】:

  • 您是否使用例如 Fiddler 比较了请求以了解它们有何不同?
  • 我没有,因为我不知道该怎么做。我会调查这个
  • PS:我意识到这是不可能的,因为我无法再使用第一个代码块的工作解决方案。我只有这个(和其他几个)sn-p 可以查看
  • 我重新获得了对原始解决方案的访问权限,我监控了新的(restsharp)数据,但 Fiddler 没有注册来自旧应用程序的流量

标签: c# asp.net-web-api xamarin restsharp


【解决方案1】:

这解决了我的问题:

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 前缀的令牌

【讨论】:

    【解决方案2】:

    试试这个

     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】:

    如果有人遇到这种情况,从 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));
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-23
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多