将HttpClient转换为RestSharp

时间:2016-03-17 13:19:05

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

我有Httpclient功能,我试图转换为RestSharp但我面临一个问题,我无法解决使用谷歌。

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

我错过了认证的内容吗?

3 个答案:

答案 0 :(得分:14)

这解决了我的问题:

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

答案 1 :(得分:5)

试试这个

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

答案 2 :(得分:0)

如果有人发生这种情况,从V 106.6.10开始,您只需向客户端添加默认参数即可避免自己将Auth令牌添加到每个请求方法中:

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      comment: {},
      some: 1
    };
  }

  handleFormChange = e => {
    e.preventDefault();
    let { comment } = this.state;
    const newCommentState = function() {
      let returnObj = { ...comment };
      returnObj[this.target.name] = this.target.value.trim();
      return returnObj;
    }.bind(e)();
    this.setState({ comment: newCommentState });
  };

  handleSubmit = e => {
    e.preventDefault();
    let { comment } = this.state;
    if (!comment.author || !comment.message) return;

    this.props.onCommentSubmit(comment);
    this.setState({ comment: {} });
    e.target[0].value = "";
    e.target[1].value = "";
  };

  render() {
    return (
      <div>
        <form
          className="ui form"
          method="post"
          onChange={e => {
            this.handleFormChange(e);
          }}
          onSubmit={e => {
            this.handleSubmit(e);
          }}
        >
          <div className="form-group">
            <input
              className="form-control"
              placeholder="user..."
              name="author"
              type="text"
            />
          </div>

          <div className="form-group">
            <textarea
              className="form-control"
              placeholder="comment..."
              name="message"
            />
          </div>

          <div className="form-group">
            <button disabled={null} className="btn btn-primary">
              Comment &#10148;
            </button>
          </div>
        </form>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);