Sending JSON strings with RestSharp

Sunday, July 27, 2014
by Sean McAlinden

This post actually applies to sending any raw body using RestSharp for any content type, the reason I have singled out JSON is because I come across this situation all the time.


Quite often I deal with strings of JSON, not nicely populated objects that I can call AddBody on a RestSharp request object for auto serialization.


Fortunately RestSharp comes with a nice way of adding any raw body values to a request, you just add the raw value with the content-type as a parameter, ensuring you specify the parameter type as ParameterType.RequestBody.


Here is an example:

var restClient = new RestClient("")
var restRequest = new RestRequest("POST");
restRequest.Resource = "myendpoint";
restRequest.AddParameter("application/json", "{\"Some\":\"Json\"}", ParameterType.RequestBody);
var response = restClient.Execute(restRequest);

So, as you can see, by passing the following items to the AddParameter method:

name: application/json

value: {\"Some\":\"Json\"}

type: ParameterType.RequestBody


We are essentially able to take full control over our POST body.