Mark Mark - 2 months ago 13
C# Question

POSTing JsonObject With HttpClient From New REST API (preview release 4)

I'm trying to POST a

JsonObject
using
HttpClient
from the new WCF Web API (preview 4). I'm not quite sure how to go about this and can't find much in the way of sample code.

Here's what I have so far:

var myObject = (dynamic)new JsonObject();
myObject.Data = "some data";
myObject.Data2 = "some more data";

HttpClient httpClient = new HttpClient("myurl");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = httpClient.Post("", ???);


I think I need to cast my
JsonObject
as a
StreamContent
but I'm getting hung up on that step.

I'm using WCF Web API Preview 4 as found at http://wcf.codeplex.com

Answer

The easiest way is to use a StringContent, with the JSON representation of your JSON object.

httpClient.Post(
    "",
    new StringContent(
        myObject.ToString(),
        Encoding.UTF8,
        "application/json"));