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
Just update your Nuget Packages into SDK .Net Core 2.1 or to the latest .Net Core SDK and it will be working.
The methodPostAsJsonAsync
(along with other *Async
methods of the HttpClient
class)
is indeed available out of the box - without using directives.
Your .csproj
file should start with <Project Sdk="Microsoft.NET.Sdk.Web">
,
and contain the lines
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
I believe this is a duplicate, and have given a more elaborated answer at https://stackoverflow.com/questions/37750451#58169080.
(The PackageReference is no longer needed in .NET Core 3.0.)
It comes as part of the library Microsoft.AspNet.WebApi.Client
https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/
You Can Use This Extension for use PostAsJsonAsync method in ASP.NET core
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
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 Task<HttpResponseMessage> PutAsJsonAsync<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.PutAsync(url, content);
}
public static async Task<T> ReadAsJsonAsync<T>(this HttpContent content)
{
var dataAsString = await content.ReadAsStringAsync().ConfigureAwait(false);
return JsonConvert.DeserializeObject<T>(dataAsString);
}
}
see: httpclient-extensions
make the extension method truly async:
public static async 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 await httpClient.PostAsync(url, content);
}
this is coming late but I think it may help someone down the line. So the *AsJsonAsync()
methods are not part of the ASP.NET Core project. I created a package that gives you the functionality. You can get it on Nuget.
https://www.nuget.org/packages/AspNetCore.Http.Extensions
using AspNetCore.Http.Extensions;
...
HttpClient client = new HttpClient();
client.PostAsJsonAsync('url', payload);