57

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 assembly.

I had thought Microsoft had changed all of the assembly names from Microsoft.AspNet to Microsoft.AspNetCore to be more specific to .NET Core, however, and yet I cannot find an Microsoft.AspNetCore.WebApi.Client assembly.

Where is the PostAsJsonAsync() extension method in ASP.NET Core?

Jeremy Caney
  • 4,585
  • 13
  • 32
  • 54
LP13
  • 20,711
  • 38
  • 136
  • 286
  • It's not part of the ASP.NET Core project, hence not following the `Microsoft.AspNetCore.*` naming schema. It's originally an extension for Windows 8/81./10/UWP/WinRT applications, which are based on `System.Runtime` and .NET Core is based on it too – Tseng Oct 13 '16 at 17:34
  • so that extension is not available in .Net Core out of the box? – LP13 Oct 13 '16 at 17:37
  • 9
    Unless you add this package to your project, nope its not available. It's `HttpClient` extension. Completely unrelated to ASP.NET or ASP.NET Core. As seen https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/ here it has no dependencies on neither ASP.NET MVC5 nor on ASP.NET Core MVC. It should work with .NET Core though, as it's a PCL which targets :NET 4.5 and Win8/8.1. You just need the `"import": [ "portable-net45+win8" ]` statement in project.json – Tseng Oct 13 '16 at 17:39
  • Possible duplicate of [Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync](http://stackoverflow.com/questions/37750451/send-http-post-message-in-asp-net-core-using-httpclient-postasjsonasync) – Set Oct 13 '16 at 18:06

14 Answers14

56

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

Oliver
  • 30,713
  • 10
  • 54
  • 69
  • 3
    I guess this should be the correct answer now. The package is available and supporting .Net standard 2.0 – Juan Jun 13 '19 at 08:41
54

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);
        }
    }
}
JenonD
  • 4,647
  • 6
  • 25
  • 32
  • 3
    That link no longer works. https://github.com/dotnet/corefx/issues/26233 Like the highly voted comment above, Microsoft now recommends the NuGet package. – Lex Li Dec 05 '18 at 01:55
11

That is not part of the ASP.NET Core project. However you can proceed with:

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://myurl/api");

string json = JsonConvert.SerializeObject(myObj);

request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

HttpClient http = new HttpClient();
HttpResponseMessage response = await http.SendAsync(request);

if (response.IsSuccessStatusCode)
    {                
    }
else
    {
    }
GorvGoyl
  • 27,835
  • 20
  • 141
  • 143
6

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

j.ghadiri
  • 310
  • 3
  • 6
5

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);
5

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

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.

Jeremy Caney
  • 4,585
  • 13
  • 32
  • 54
  • 2
    This solution also works for .NET Core 3.0 and newer. You need to add NuGet package `System.Net.Http.Json` – nt86 Oct 22 '20 at 09:42
2

You need to add Nuget package System.Net.Http.Formatting.Extension to your project.

Or you can use

client.PostAsync(uri, new StringContent(data, Encoding.UTF8, "application/json"));
ANJYR
  • 2,347
  • 4
  • 34
  • 57
2

To follow on from the answers above, I have a small addition that was required for me to get it to work.

Previously I was using a .NET Core 2.1 web app using the PostAsJsonAsync() method, and when I upgraded to .NET Core 3.1 it no longer worked.

I could not get the above answers to work, and it turned out to be because the text to be posted had to be surrounded by quotes, and any quotes within it had to be escaped. I made the following extension method, which solved my problem:

public static async Task<HttpResponseMessage> PostJsonAsync(this HttpClient client, string uri, string json)
{
    //For some reason, not doing this will cause it to fail:
    json = $"\"{json.Replace("\"", "\\\"")}\"";

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

Note that I am using the System.Text.Json.JsonSerializer as opposed to the Newtonsoft version.

Greg
  • 1,529
  • 3
  • 17
  • 26
0

Just update your Nuget Packages into SDK .Net Core 2.1 or to the latest .Net Core SDK and it will be working.

Israel Ocbina
  • 411
  • 6
  • 10
0

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);
}
barbsan
  • 3,238
  • 11
  • 18
  • 27
f.capet
  • 19
  • 2
0

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.)

Henke
  • 1,466
  • 2
  • 9
  • 22
0

If you are trying to use PostJsonAsync, PutJsonAsync or any other json extension methods in Blazor you need to add a following statement

using Microsoft.AspNetCore.Components;
0

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/main/accepted/2020/json-http-extensions/json-http-extensions.md

Bambam Deo
  • 135
  • 4
  • 14
erandac
  • 559
  • 5
  • 8
-3
using Microsoft.AspNetCore.Blazor.HttpClient
Craiqser
  • 1
  • 1
  • 1
    I can't find any evidence that this exists in this class—or, in fact, even find this class's documentation. I'm not saying it doesn't exist, only that it's going to be hard for readers to find information on how to use it with only a namespace reference. Can you update your answer to include, at minimum, a working example and, ideally, a link to the documentation? Also, is this dependent on the [`Microsoft.AspNetCore.Blazor.HttpClient`](https://www.nuget.org/packages/Microsoft.AspNetCore.Blazor.HttpClient/) (preview) package? If so, be sure to note that. – Jeremy Caney Jun 13 '20 at 20:16
  • [The best documentation I can find](https://docs.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-3.1) actually points to the .NET 5.0 (preview) BCL—which, if you're using that, you don't need to rely on the Blazor package. I've [added an answer](https://stackoverflow.com/a/62365042/3025856) that provides information on the .NET 5.0 version, for those in the process of migrating from .NET Core to .NET 5.0. – Jeremy Caney Jun 13 '20 at 20:34