I'm a bit unsure on how to do my post request in C#. I have tried doing it in Postman and it works there without problem. I think my problem is json formatting. I construct my json with JObjects in the Newtonsoft library. When the code below is run, this is the output; {"accountreference":"XX","messages":"[{\r\n \"to\": \"+XXXXX\",\r\n \"body\": \"XXXXXXXX\"\r\n}]"}
It is valid, but as you can see it contains linebreaks and escape characters. Upon posting it to the api I am using, I always get back a 400 bad request.
I've tried various serializers and techniques but not been able to get it working. I've also made sure that the Authroization header is correct, if it was incorrect the API should have said so in its return message. According to the developers of the API, this message should only happen if the body is incorrect. I've tried posting the string with linebreaks in Postman and that also yields 400. Is there a easy way to get rid of them?
var tmpObj = new JObject {{"to", to}, {"body", message}};
var jsonObj = new JObject
{
{"accountreference", MessageConfiguration.Ref}, {"messages", "[" + tmpObj + "]"}
};
var json = jsonObj.ToString(Formatting.None);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var url = new Uri("www.xxxxxxxx/hjdhsf");
return await PostAsync(url, httpContent);
protected async Task<HttpResponseMessage> PostAsync(Uri endpoint, HttpContent content)
{
using (var httpClient = NewHttpClient())
{
var result = await httpClient.PostAsync(endpoint, content);
return result; //Statuscode is 400 here.
}
}
This valid json works in Postman:
{
"accountreference":"XXXXX",
"messages":[{
"to":"XXXXX",
"body":"XXX!"
}]
}
Update:
According to answer, I tried this:
var body = new
{
accountreference = MessageConfiguration.Ref,
messages = new[]
{
new
{
to = to,
body = message
}
}
};
var json = new JavaScriptSerializer().Serialize(body);
Now the json looks correct and I could even copy it from VS into postman and it worked. However my reqests in VS still returns 400.