Where is the PostAsJsonAsync method in ASP.NET Core?

It comes as part of the library Microsoft.AspNet.WebApi.Client https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/


I dont deserve any credit for this. Have a look @danroth27 answer in the following link.

https://github.com/aspnet/Docs/blob/master/aspnetcore/mvc/controllers/testing/sample/TestingControllersSample/tests/TestingControllersSample.Tests/IntegrationTests/HttpClientExtensions.cs

He uses an extension method. Code as below. (Copied from the above github link). I am using it on .Net Core 2.0.

using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace TestingControllersSample.Tests.IntegrationTests
{
    public static class HttpClientExtensions
    {
        public static Task<HttpResponseMessage> PostAsJsonAsync<T>(
            this HttpClient httpClient, string url, T data)
        {
            var dataAsString = JsonConvert.SerializeObject(data);
            var content = new StringContent(dataAsString);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return httpClient.PostAsync(url, content);
        }

        public static async Task<T> ReadAsJsonAsync<T>(this HttpContent content)
        {
            var dataAsString = await content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<T>(dataAsString);
        }
    }
}

As of .NET 5.0, this has been (re)introduced as an extension method off of HttpClient, via the System.Net.Http.Json namespace. See the HttpClientJsonExtensions class for details.

Demonstration

It works something like the following:

var httpClient  = new HttpClient();
var url         = "https://StackOverflow.com"
var data        = new MyDto();
var source      = new CancellationTokenSource();

var response    = await httpClient.PostAsJsonAsync<MyDto>(url, data, source.Token);

And, of course, you'll need to reference some namespaces:

using System.Net.Http;          //HttpClient, HttpResponseMessage
using System.Net.Http.Json;     //HttpClientJsonExtensions
using System.Threading;         //CancellationToken
using System.Threading.Tasks;   //Task

Alternatively, if you're using the .NET 6 SDK's implicit using directives, three of these will be included for you, so you'll just need:

using System.Net.Http.Json;     //HttpClientJsonExtensions

Background

This is based on the design document, which was previously referenced by @erandac—though the design has since changed, particularly for the PostAsJsonAsync() method.

Obviously, this doesn't solve the problem for anyone still using .NET Core, but with .NET 5.0 released, this is now the best option.