RestSharp Accept header change

2020-07-09 10:21发布

问题:

I am using RestSharp for developing on the client side. I am also using Ruby Grape gem for my custom API on server side. Grape gem can do versioning by setting Accept HTTP header f.e to application/vnd.twitter-v1+json

And test command via console works perfect

curl -H Accept=application/vnd.twitter-v1+json /statuses/public_timeline

But when I am trying to set up header for RestRequest I am getting error 404 on the server.

I have no idea why so. I have found another issue that server returns 406 error - but in my case 404.

How can I put custom value for Accept header?

回答1:

You can set a custom Accept header with the AddHeader method...

var client = new RestClient("http://example.com/api");
var request = new RestRequest("statuses/public_timeline", Method.GET);
request.AddHeader("Accept", "application/vnd.twitter-v1+json");
var response = client.Execute(request);
var json = response.Content;

This should work fine if you are willing to deserialize the JSON yourself.


If you want to make use of the generic Execute<T> method, which does automatic deserialization for you, you will run into problems...

From the RestSharp documentation about deserialization:

RestSharp includes deserializers to process XML and JSON. Upon receiving a response, RestClient chooses the correct deserializer to use based on the Content Type returned by the server. The defaults can be overridden (see Customization). The built-in content types supported are:

  • application/json – JsonDeserializer
  • application/xml – XmlDeserializer
  • text/json – JsonDeserializer
  • text/xml – XmlDeserializer
  • * – XmlDeserializer (all other content types not specified)

This is saying that, by default, if the response's content type is not one of those listed, RestSharp will attempt to use the XmlDeserializer on your data. This is customizable though with extra work.