Search code examples
c#http-headersrestsharp

Set 'Content-Type' header using RestSharp


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?


Solution

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