Where is PostAsJsonAsync method in ASP.NET Core?

纵然是瞬间 提交于 2019-11-29 16:39:48

问题


I was looking for PostAsJsonAsync extension method in ASP.NET core. Based on article here its available in Microsoft.AspNet.WebApi.Client assembly. However i though Microsoft has changed all the assembly names from Microsoft.AspNet to Microsoft.AspNetCore to be more specific with .Net Core framework. But i could not find Microsoft.AspNetCore.WebApi.Client

Where is PostAsJsonAsync extension method in ASP.NET core?


回答1:


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



回答2:


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




回答3:


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
    {
    }



回答4:


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:


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




回答6:


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



回答7:


This is theoretical...

public static async System.Threading.Tasks.Task<HttpResponseMessage> PostJsonAsync(object dataclass, string Url)
    {
        using (var client = new HttpClient())
            return await client.PostAsync(Url, new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(dataclass), System.Text.Encoding.UTF8, "application/json"));
    }

...Fingers crossed.




回答8:


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



回答9:


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




回答10:


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




回答11:


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;


来源:https://stackoverflow.com/questions/40027299/where-is-postasjsonasync-method-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!