简体   繁体   English

RestSharp接受标头更改

[英]RestSharp Accept header change

I am using RestSharp for developing on the client side. 我正在使用RestSharp在客户端进行开发。 I am also using Ruby Grape gem for my custom API on server side. 我也在服务器端使用Ruby Grape gem作为我的自定义API。 Grape gem can do versioning by setting Accept HTTP header fe to application/vnd.twitter-v1+json Grape gem可以通过将Accept HTTP标头设置为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. 但是,当我尝试为RestRequest设置标头时,我在服务器上收到error 404

I have no idea why so. 我不知道为什么会这样。 I have found another issue that server returns 406 error - but in my case 404. 我发现服务器返回406 error另一个问题 - 但在我的情况下404。

How can I put custom value for Accept header? 如何为Accept标头添加自定义值?

You can set a custom Accept header with the AddHeader method... 您可以使用AddHeader方法设置自定义Accept标头...

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. 如果您愿意自己反序列化JSON,这应该可以正常工作。


If you want to make use of the generic Execute<T> method, which does automatic deserialization for you, you will run into problems... 如果你想使用通用的Execute<T>方法,它会为你做自动反序列化,你会遇到问题......

From the RestSharp documentation about deserialization : RestSharp文档中有关反序列化的信息

RestSharp includes deserializers to process XML and JSON. RestSharp包含用于处理XML和JSON的反序列化器。 Upon receiving a response, RestClient chooses the correct deserializer to use based on the Content Type returned by the server. 收到响应后,RestClient会根据服务器返回的内容类型选择正确的反序列化器。 The defaults can be overridden (see Customization). 可以覆盖默认值(请参阅自定义)。 The built-in content types supported are: 支持的内置内容类型包括:

  • application/json – JsonDeserializer application / json - JsonDeserializer
  • application/xml – XmlDeserializer application / xml - XmlDeserializer
  • text/json – JsonDeserializer text / json - JsonDeserializer
  • text/xml – XmlDeserializer text / xml - XmlDeserializer
  • * – XmlDeserializer (all other content types not specified) * - XmlDeserializer(未指定所有其他内容类型)

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. 这就是说,默认情况下,如果响应的内容类型不是列出的内容类型,RestSharp将尝试在您的数据上使用XmlDeserializer。 This is customizable though with extra work. 这可以通过额外的工作进行定制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM