繁体   English   中英

使用 RestSharp 设置“Content-Type”标头

[英]Set 'Content-Type' header using RestSharp

我正在为 RSS 阅读服务构建一个客户端。 我正在使用RestSharp库与他们的 API 进行交互。

API 指出:

创建或更新记录时,您必须将application/json;charset=utf-8Content-Type标头。

这是我的代码的样子:

RestRequest request = new RestRequest("/v2/starred_entries.json", Method.POST);
request.AddHeader("Content-Type", "application/json; charset=utf-8");
request.RequestFormat = DataFormat.Json;
request.AddParameter("starred_entries", id);

//Pass the request to the RestSharp client
Messagebox.Show(rest.ExecuteAsPost(request, "POST").Content);

然而; 服务返回错误

错误 415:请使用“内容类型:应用程序/json; charset=utf-8' 标头

为什么 RestSharp 不传递标题?

我博客上提供的解决方案没有经过 RestSharp 1.02 版以外的测试。 如果您就我的解决方案的具体问题提交对我的回答的评论,我可以更新它。

var client = new RestClient("http://www.example.com/where/else?key=value");
var request = new RestRequest();

request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", strJSONContent, ParameterType.RequestBody);

var response = client.Execute(request);

在 105.2.3.0 版本中,我可以这样解决问题:

var client = new RestClient("https://www.example.com");
var request = new RestRequest("api/v1/records", Method.POST);
request.AddJsonBody(new { id = 1, name = "record 1" });
var response = client.Execute(request);

老问题,但仍然是我搜索的首要问题 - 添加完整性。

虽然这有点旧:我遇到了同样的问题..似乎某些属性(例如“内容类型”或“日期”)不能作为参数添加,而是在内部添加。 要更改“内容类型”的值,我必须更改序列化器设置(虽然我没有使用它,因为我在之前序列化的主体中添加了一个 json!)

RestClient client = new RestClient(requURI);
RestRequest request = new RestRequest(reqPath, method);
request.JsonSerializer.ContentType = "application/json; charset=utf-8";

一旦我这样做,标题就会按预期显示:

 System.Net Information: 0 : [5620] ConnectStream#61150033 -   Header 
 {
  Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
  User-Agent: RestSharp 104.1.0.0
  Content-Type: application/json; charset=utf-8
  ...
 }

您很可能会遇到这个问题: https : //github.com/restsharp/restsharp/issues/221您的问题有一个可行的解决方案@ http://itanex.blogspot.co.at/2012/02/restsharp- and-advanced-post-requests.html

request.XmlSerializer = new DotNetXmlSerializer();
            request.Parameters.Clear();
            request.AddParameter(new Parameter()
            {
                ContentType = "application/xml",
                Name = "application/xml",
                Type = ParameterType.RequestBody,
                Value = request.XmlSerializer.Serialize(deleteUserQuery.UserDelRqHeader)
            });
            request.AddHeader("Accept", "application/xml");

这是解决方案

http://restsharp.blogspot.ca/

创建一个具有相同名称属性的 json 对象并设置值(确保它们与 post 请求的名称值对相似。)

之后使用默认的httpclient。

暂无
暂无

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

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