How to post JSON with HttpClient using C#?

Louis picture Louis · Feb 12, 2015 · Viewed 16.5k times · Source

I have no idea how to POST JSON with HttpClient. I find some solution, like this, but I have to use HttpClient, cause of async and have to add a header.

This is my code below. Any idea how to fix it?

List<Order> list = new List<Order> { new Order() { Name = "CreatedTime", OrderBy = 1 } };

Queues items = new Queues { Orders = list };

var values = new Dictionary<string, string> { { "Orders", JsonConvert.SerializeObject(list) } };

var content = new FormUrlEncodedContent(values);

//HttpContent cc = new StringContent(JsonConvert.SerializeObject(items));

_msg = await _client.PostAsync(input, content);

//_msg = await _client.PostAsync(input, cc);

var response = await _msg.Content.ReadAsStringAsync();

Answer

Peter Mols picture Peter Mols · Feb 12, 2015

You can use the method PostAsJsonAsync which can be found in the extensions assemblies:

System.Net.Http.Formatting.dll

Example

public static async Task SendJsonDemo(object content)
{
    using(var client = new HttpClient())
    {
        var response = await client.PostAsJsonAsync("https://example.com", content);
    }
}

If you want to add custom headers to the request, add it to DefaultRequestHeaders:

client.DefaultRequestHeaders.Add("mycustom", "header1");