ASP.NET Core中的PostAsJsonAsync方法在哪里? [英] Where is PostAsJsonAsync method in ASP.NET Core?
问题描述
我正在ASP.NET核心中寻找 PostAsJsonAsync
扩展方法。根据文章此处在 Microsoft.AspNet.WebApi.Client
程序集中可用。但是,尽管我已经将Microsoft的所有程序集名称从 Microsoft.AspNet
更改为 Microsoft.AspNetCore
,以使其更加具体。网络核心框架。但是我找不到 Microsoft.AspNetCore.WebApi.Client
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
哪里是 PostAsJsonAsync
ASP.NET核心中的扩展方法?
Where is PostAsJsonAsync
extension method in ASP.NET core?
推荐答案
我对此不负任何责任。在以下链接中查看@ danroth27答案。
I dont deserve any credit for this. Have a look @danroth27 answer in the following link.
他使用扩展方法。代码如下。 (从上面的github链接复制)。我在.Net Core 2.0上使用它。
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);
}
}
}
这篇关于ASP.NET Core中的PostAsJsonAsync方法在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!