Search code examples
jsonuwphttpclienthttpcontent

No content when using PostAsync to post JSON


Using the code below, I've managed to create a jsonArray with the following format:[{"id":3},{"id":4},{"id":5}]

var jArray = new JsonArray();
        int numOfChildren = 10;
        for (int i = 0; i < numOfChildren; i++)
        {
            if (CONDITION == true)
            {
                var jObj = new JsonObject();
                int id = SOMEID;
                jObj.SetNamedValue("id", JsonValue.CreateNumberValue(id));
                jArray.Add(jObj);
            }

I am now trying to send "JsonArray" to a server using PostAsync as can be seen below:

Uri posturi = new Uri("http://MYURI");
HttpContent content = new StringContent(jArray.ToString(), Encoding.UTF8, "application/json");
System.Net.Http.HttpResponseMessage response = await client.PostAsync(postUri, content);

On the server side of things though, I can see that the post request contains no content. After digging around on the interwebs, it would seem that using jArray.ToString() within StringContent is the culprit, but I'm not understanding why or if that even is the problem in the first place. So, why is my content missing? Note that I'm writing this for UWP aplication that does not use JSON.net.


Solution

  • After much digging, I eventually Wiresharked two different applications, one with my original jArray.ToString() and another using JSON.net's JsonConver.SerializeObject(). In Wireshark, I could see that the content of the two packets was identical, so that told me that my issue resided on the server side of things. I eventually figured out that my PHP script that handled incoming POST requests was too literal and would only accept json posts of the type 'application/json'. My UWP application sent packets of the type 'application/json; charset=utf-8'. After loosening some of my content checking on the server side a bit, all was well.

    For those who are looking to serialize json without the use of JSON.net, jsonArray.ToString() or jsonArray.Stringify() both work well.