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

.net-core, asp.net-core, c#

Solution

If you are using .NET 5 or above, you can (and should) use the `PostAsJsonAsync` extension method from System.Net.Http.Json:

httpClient.PostAsJsonAsync(url, new { 
    x = 1, 
    y = 2 
});

If you are using an older version of .NET Core, you can implement the extension function yourself:

public static class HttpClientExtensions
{
    public static Task<HttpResponseMessage> PostJsonAsync(this HttpClient httpClient, string url, object body)
    {
        var bodyJson = JsonSerializer.Serialize(body);
        var stringContent = new StringContent(bodyJson, Encoding.UTF8, "application/json");
        return httpClient.PostAsync(url, stringContent);
    }
}

Problem

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?

Original source