Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

Rem picture Rem · Jun 10, 2016 · Viewed 164.5k times · Source

I want to send dynamic object like

new { x = 1, y = 2 };

as body of HTTP POST message. So I try to write

var client = new HttpClient();

but I can't find method

client.PostAsJsonAsync()

So I tried to add Microsoft.AspNetCore.Http.Extensions package to project.json and add

using Microsoft.AspNetCore.Http.Extensions; 

to uses clause. However It didn't help me.

So what is the easiest way to send POST request with JSON body in ASP.NET Core?

Answer

Set picture Set · Jun 10, 2016

You should add reference to "Microsoft.AspNet.WebApi.Client" package (read this article for samples).

Without any additional extension, you may use standard PostAsync method:

client.PostAsync(uri, new StringContent(jsonInString, Encoding.UTF8, "application/json"));

where jsonInString value you can get by calling JsonConvert.SerializeObject(<your object>);