39

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Shane Gowland
  • 832
  • 1
  • 9
  • 10
  • I'm not familiar with RestSharp, but I would use Fiddler to inspect the request to be sure about what RestSharp IS passing. It may be that the Content-Type header has already been added and you need to replace or remove/add it. I would assume that `request.RequestFormat = DataFormat.Json` is setting the Content-Type header for you. – Randy James Jul 23 '13 at 17:59
  • I've tried it with our without that line. The only option is JSON or XML. – Shane Gowland Jul 24 '13 at 07:05
  • Please post how the request looks in Fiddler, that will tell whether and what Content-Type has been added, without that it is just guessing. – Darius Jul 24 '13 at 12:22
  • Done. It seems the header isn't being added. See: http://pastebin.com/B0MjHrgD – Shane Gowland Jul 24 '13 at 15:30
  • See the answer below by CodeCaster, as well as my comments about name/value parameter types – drewid Dec 22 '15 at 07:45

5 Answers5

70

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);
Itanex
  • 1,664
  • 21
  • 33
  • 2
    In the context of my specific situation, what should the 'strJSONContent' variable contain? – Shane Gowland Jul 30 '13 at 10:38
  • 1
    strJSONContent is the JSON string that represents your data to be sent during the POST request. This must be valid JSON so that the server can interpret it correctly. When working with RestSharp and examining the parameter that contains your JSON string, the result will contains the mimetype and the data as follows: "application/json={\"key1\":\"value1\",\"key2\":\"value2\"}" – Itanex Jul 30 '13 at 18:57
  • 1
    var body = new Dictionary() {{"starred_entries", id}}; strJSONContent = request.JsonSerializer.Serialize(body); – Alex Che Dec 16 '15 at 09:47
  • 1
    The key is that you cannot have any regular name/value parameters via request.AddParameter. If you need them in the url, you have to add that to either the client url or the request resource url. You CAN have authorization and requestbody parameter types. Once I changed this my json in the body was sent correctly. – drewid Dec 22 '15 at 07:44
  • And my comments are that .AddParameter does not work with POST. Works fine with GET – drewid Jan 08 '16 at 05:24
  • @drewid in 2012 V1.02 of restsharp did not have the facilities to denote path variable replacement and post body content. Therefore, you have to manually construct the URI if you are posting against a data driven URI. Unfortunate, I know. I have had suggestions that the interfaces of RestSharp have changed since I posted, though I have adopted the HTTPClient over RestSharp for the majority of my projects as of late. Perhaps it is time to check out RestSharp and see how it is doing. – Itanex Feb 19 '16 at 08:43
  • Have an issue: Parameters.clear() removes the authorisation header. Why is clearing required? – Dasith Wijes Feb 15 '17 at 05:29
  • @Itanex ..I know it's been a while but even after long time, the solution provided in your blog worked for me. Thank you.. – Scorpy47 May 20 '20 at 06:19
40

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.

Tom Elmore
  • 1,980
  • 15
  • 20
  • This is the most elegant solution for the current version of restsharp 105.2.3 – BrokeMyLegBiking Mar 17 '17 at 13:22
  • 1
    this doesnt mention how to add the content-type headers - can you elaborate at all? – Paul Mar 23 '18 at 10:45
  • 3
    Hey @Paul - I seem to remember they get added automagically when you call AddJsonBody. It was a while ago that I used it though. – Tom Elmore Mar 26 '18 at 14:17
  • Does it work with HTTP GET ? (I ask because just changing from POST to GET, with the same JSON content, I have a NullObjectReferenceException but the code is way out complicated than a basic example) With Postman it works, only using RestSharp we have the error. – Alex 75 Jan 14 '19 at 17:07
  • Hey @Alex75 - I tried it out with LINQPad and Fiddler and while it does not error, it also doesnt add a body to the request. I imagine the response doesnt contain what you expect and the handling code exceptions as a result. This might also interest you : https://stackoverflow.com/questions/978061/http-get-with-request-body – Tom Elmore Jan 15 '19 at 14:06
  • Ah. Thanks for the link, it is really explanatory! The bad news is that I "fought" with my colleagues to change a search request (the logging says "GET Account balance bla bla bla") currently done with a POSTm using the GET HTTP method. It works well until we pass through the RestSharp "layer" we created to redirect the calls. Now, because they will not allow me to use a GET+querystring instead of the current JSON body content I have to live with ther POST + body content to actually making a _search_ on the backend. So sad :-( . Thanks again for the reply. – Alex 75 Jan 15 '19 at 17:48
  • I expected an error doing this with a GET instead of _silently_ ignoring to add the body. I'm curious to try with Flurl. – Alex 75 Jan 15 '19 at 17:52
12

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
  ...
 }
Marc Wittmann
  • 2,286
  • 2
  • 28
  • 41
3

You most probably run into this problem: https://github.com/restsharp/restsharp/issues/221 There is a working solution to your problem @ http://itanex.blogspot.co.at/2012/02/restsharp-and-advanced-post-requests.html

D.R.
  • 20,268
  • 21
  • 102
  • 205
  • I haven't succeeded in getting that solution working; it still reverts the content-type to `application/x-www-form-urlencoded` – Shane Gowland Jul 29 '13 at 05:34
-4

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.

  • 1
    This is not constructive. The question is regarding RestSharp. Instructing the user to not use RestSharp does not solve the problem. – Itanex Jul 31 '18 at 21:08