Set 'Content-Type' header using RestSharp

2020-02-04 06:53发布

I'm building a client for an RSS reading service. I'm using the RestSharp library to interact with their API.

The API states:

When creating or updating a record you must set application/json;charset=utf-8 as the Content-Type header.

This is what my code looks like:

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

However; the service is returning an error

Error 415: Please use the 'Content-Type: application/json; charset=utf-8' header

Why isn't RestSharp passing the header?

5条回答
叼着烟拽天下
2楼-- · 2020-02-04 07:04

Here is the solution

http://restsharp.blogspot.ca/

Create a json object with same name properties and set the values (Make sure they are similar to those of name value pair for post request.)

After that use default httpclient.

查看更多
淡お忘
3楼-- · 2020-02-04 07:10

In version 105.2.3.0 I can solve the problem this way:

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

Old question but still top of my search - adding for completeness.

查看更多
戒情不戒烟
4楼-- · 2020-02-04 07:20

Although this is a bit old: I ran into the same problem.. seems some attributes such as "content-type" or "date" cannot be added as parameter but are added internally. To alter the value of "content-type" I had to change the serialzer setting (altough I didn`t use it because I added a json in the body that was serialized before!)

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

as soon as I did this the header showed up as intended:

 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
  ...
 }
查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-02-04 07:24
不美不萌又怎样
6楼-- · 2020-02-04 07:26

The solution provided on my blog is not tested beyond version 1.02 of RestSharp. If you submit a comment on my answer with your specific issue with my solution, I can update it.

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);
查看更多
登录 后发表回答