I am using RestSharp to make a POST request containing a JSON body. But I get a Bad request error.
Because I have []
and ""
in my JSON I have decided to use Newtonsoft.Json . Before using this I couldn't even see a JSON request being formed.
I am willing to try MS httpwebrequest
as an alternative.
restClient = new RestClient();
restRequest = new RestRequest(ApiUrl, Method.POST, DataFormat.Json);
var myObject = "{ \"target\" : \"[5,5]\", \"lastseen\" : \"1555459984\" }";
var json = JsonConvert.SerializeObject(myObject);
restRequest.AddParameter("application/json", ParameterType.RequestBody);
restRequest.AddJsonBody(json);
Please note that I am trying to convert a JSON curl to C#. Please see below:
curl -H 'Content-Type: application/json' -X POST -d '{ "target" : [5, 5], "lastseen" : "1555459984", "previousTargets" : [ [1, 0], [2, 2], [2, 3] ] }' http://santized/santized/santized
You appear to be over serializing the data to be sent.
Consider creating an object and then passing it to AddJsonBody
.
//...
restClient = new RestClient();
restRequest = new RestRequest(ApiUrl, Method.POST, DataFormat.Json);
var myObject = new {
target = new []{ 5, 5 },
lastseen = "1555459984",
previousTargets = new []{
new [] { 1, 0 },
new [] { 2, 2 },
new [] { 2, 3 }
}
};
restRequest.AddJsonBody(myObject); //this will serialize the object and set header
//...
AddJsonBody
sets content type to application/json
and serializes the object to a JSON string.