RestSharp Accept header change

Ihor picture Ihor · May 19, 2013 · Viewed 12.6k times · Source

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?

Answer

Jesse Webb picture Jesse Webb · Aug 9, 2013

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.