Where is the PostAsJsonAsync method in ASP.NET Core?

后端 未结 14 1750
再見小時候
再見小時候 2020-12-29 00:51

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

相关标签:
14条回答
  • 2020-12-29 01:49

    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.

    0 讨论(0)
  • 2020-12-29 01:50

    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

    0 讨论(0)
提交回复
热议问题