ASP.NET Core中的PostAsJsonAsync方法在哪里? [英] Where is the PostAsJsonAsync method in ASP.NET Core?
问题描述
我正在ASP.NET Core中寻找PostAsJsonAsync()
扩展方法.
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.
我以为Microsoft已将所有程序集名称从Microsoft.AspNet
更改为Microsoft.AspNetCore
,以更特定于.NET Core,但我却找不到Microsoft.AspNetCore.WebApi.Client
程序集.
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.
ASP.NET Core中PostAsJsonAsync()
扩展方法在哪里?
Where is the 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屋!