Set 'Content-Type' header using RestSharp

104,532

Solution 1

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

Solution 2

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.

Solution 3

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
  ...
 }

Solution 4

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

Share:
104,532
Shane Gowland
Author by

Shane Gowland

Updated on November 22, 2020

Comments

  • Shane Gowland
    Shane Gowland over 3 years

    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?

  • Shane Gowland
    Shane Gowland almost 11 years
    I haven't succeeded in getting that solution working; it still reverts the content-type to application/x-www-form-urlencoded
  • Shane Gowland
    Shane Gowland almost 11 years
    In the context of my specific situation, what should the 'strJSONContent' variable contain?
  • Itanex
    Itanex almost 11 years
    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\"}"
  • osjerick
    osjerick over 8 years
    var body = new Dictionary<string, string>() {{"starred_entries", id}}; strJSONContent = request.JsonSerializer.Serialize(body);
  • drewid
    drewid over 8 years
    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
    drewid over 8 years
    And my comments are that .AddParameter does not work with POST. Works fine with GET
  • Itanex
    Itanex over 8 years
    @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.
  • Dasith Wijes
    Dasith Wijes over 7 years
    Have an issue: Parameters.clear() removes the authorisation header. Why is clearing required?
  • BrokeMyLegBiking
    BrokeMyLegBiking over 7 years
    This is the most elegant solution for the current version of restsharp 105.2.3
  • Paul
    Paul over 6 years
    this doesnt mention how to add the content-type headers - can you elaborate at all?
  • Tom Elmore
    Tom Elmore over 6 years
    Hey @Paul - I seem to remember they get added automagically when you call AddJsonBody. It was a while ago that I used it though.
  • Itanex
    Itanex almost 6 years
    This is not constructive. The question is regarding RestSharp. Instructing the user to not use RestSharp does not solve the problem.
  • Itanex
    Itanex almost 6 years
    Could you update this with the version that you are using. It helps provide details to the user. :)
  • Alex 75
    Alex 75 over 5 years
    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.
  • Tom Elmore
    Tom Elmore over 5 years
    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 : stackoverflow.com/questions/978061/http-get-with-request-bod‌​y
  • Alex 75
    Alex 75 over 5 years
    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
    Alex 75 over 5 years
    I expected an error doing this with a GET instead of silently ignoring to add the body. I'm curious to try with Flurl.
  • Scorpy47
    Scorpy47 about 4 years
    @Itanex ..I know it's been a while but even after long time, the solution provided in your blog worked for me. Thank you..
  • Ismail Hawayel
    Ismail Hawayel over 3 years
    to me, this is much cleaner as you do not have to blindly clear parameters and looks more to the point, thank you.