POSTing JsonObject With HttpClient From Web API

Mark picture Mark · May 24, 2011 · Viewed 368.4k times · Source

I'm trying to POST a JsonObject using HttpClient from Web API. 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.

Answer

pomber picture pomber · Sep 9, 2016

With the new version of HttpClient and without the WebApi package it would be:

var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var result = client.PostAsync(url, content).Result;

Or if you want it async:

var result = await client.PostAsync(url, content);