I want to send a bunch of data, converted to json, as a string, to a Web API POST method. I can send a simple string just fine, but when I try to send stringified json data, the method is not even reached - apparently the complex string is not viewed as a valid string value or something.
This works, when passing "randomString" from the client:
[Route("{unit}/{begindate}/{enddate}/{stringifiedjsondata}")]
[HttpPost]
public void Post(string unit, string begindate, string enddate, string stringifiedjsondata)
{
// test
string jsonizedData = stringifiedjsondata;
string dataAsJson = "randomString";
String uriToCall = String.Format("/api/produceusage/{0}/{1}/{2}/{3}", _unit, beginRange, endRange, dataAsJson);
HttpResponseMessage response = await client.PostAsync(uriToCall, null);
When the string is json data, such as this:
[
{
"ItemDescription": "DUCKBILLS, GRAMPS-EIER 70CT 42#",
"PackagesMonth1": 1467, . . . }]
...it does not work. I create this string by converting a generic list to json using JSON.NET like so:
string dataAsJson = JsonConvert.SerializeObject(_rawAndCalcdDataAmalgamatedList, Formatting.Indented);
String uriToCall = String.Format("/api/produceusage/{0}/{1}/{2}/{3}", _unit, beginRange, endRange, dataAsJson);
HttpResponseMessage response = await client.PostAsync(uriToCall, null);
So the only difference is in the string; when it's something simple like "randomString" I reach this line in the Web API POST method:
string jsonizedData = stringifiedjsondata;
...but when it's a complex string, such as stringified json data, that line is not reached.
Why? And how can I fix the stringified json data so that it is received and recognized?
You are having troubles because you are sending the JSON to your API through the URL. I suggest you to send it in the body content of your request. In order to do it, change your Web Api method like this:
[Route("{unit}/{begindate}/{enddate}")]
[HttpPost]
public void Post(string unit, string begindate, string enddate, [FromBody] string stringifiedjsondata)
{
// test
string jsonizedData = stringifiedjsondata;
}
Also change your Winforms client code:
string dataAsJson = "[{\"ItemDescription\": \"DUCKBILLS, GRAMPS-EIER 70CT 42#\",\"PackagesMonth1\": 1467}]";
String uriToCall = String.Format("/api/produceusage/{0}/{1}/{2}", _unit, beginRange, endRange);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("", dataAsJson)
});
HttpResponseMessage response = await client.PostAsync(uriToCall, content);
Now it should work as you expected. Check this link about the HTTP Client library in order to see more examples about sending data to an API if you need it.