I was looking for the PostAsJsonAsync()
extension method in ASP.NET Core. Based on this article, it\'s available in the Microsoft.AspNet.WebApi.Client
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.
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
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.
Dotnet core 3.x runtime itself going to have set of extension methods for HttpClient which uses System.Text.Json Serializer
https://github.com/dotnet/designs/blob/master/accepted/2020/json-http-extensions/json-http-extentions.md