[英]Has HttpContent.ReadAsAsync<T> method been superceded in .NET Core?
The following refers to a .NET Core application with dependencies as follows...以下是指一个 .NET Core 应用,依赖如下...
Microsoft.NETCore.App
Microsoft.AspNet.WepApi.Client (5.2.7)
At Microsoft.com is the document Call a Web API From a .NET Client (C#)
from 2017 November.在 Microsoft.com 是文档
Call a Web API From a .NET Client (C#)
。
Link... https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client链接... https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client
Within the document is this client side invocation of HTTP GET.在文档中是 HTTP GET 的客户端调用。
static HttpClient client = new HttpClient();
static async Task<Product> GetProductAsync(string path)
{
Product product = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
product = await response.Content.ReadAsAsync<Product>();
}
return product;
}
The value response.Content
refers to an HttpContent
object.值
response.Content
指的是HttpContent
object。 As of 2020 July HttpContent
has no instance method with the signature ReadAsAsync<T>()
, at least according to the following document.截至 2020 年 7 月,
HttpContent
没有签名ReadAsAsync<T>()
的实例方法,至少根据以下文档。 However, this instance method works.但是,此实例方法有效。
Reference link to where there is no instance method with the signature ReadAsAsync<T>()
... https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent?view=netcore-3.1没有带有签名的实例方法的参考链接ReadAsAsync
ReadAsAsync<T>()
... -3.1
There is a static method HttpContentExtensions.ReadAsAsync<T>(myContent)
where myContent
refers to an HttpContent
object.有一个 static 方法
HttpContentExtensions.ReadAsAsync<T>(myContent)
其中myContent
指的是HttpContent
object。 This static method also works.此 static 方法也有效。
Reference link... https://docs.microsoft.com/en-us/previous-versions/aspnet/hh834253(v=vs.118)参考链接... https://docs.microsoft.com/en-us/previous-versions/aspnet/hh834253(v=vs.118)
For example one documented signature has the...例如,一个记录在案的签名具有...
static icon followed by
ReadAsAsync<T>(HttpContent)
static 图标后跟
ReadAsAsync<T>(HttpContent)
and a description that says it will return Task<T>
.以及说明它将返回
Task<T>
的描述。 This static method is probably the behind the scenes implementation of the instance method.这个 static 方法可能是实例方法的幕后实现。
However there is information at the top of the static method webpage that indicates... " We're no longer updating this content regularly. Check the Microsoft Product Lifecycle for information about how this product, service, technology, or API is supported. "但是,static 方法网页顶部的信息表明...“我们不再定期更新此内容。请查看 Microsoft 产品生命周期以获取有关如何支持此产品、服务、技术或 API 的信息。 ”
Has HttpContent.ReadAsAsync<T>()
of both forms, instance and static, been superceded in .NET Core 3.1? forms 实例和 static 的
HttpContent.ReadAsAsync<T>()
是否已在 .NET Core 3.1 中被取代?
I can't tell from the code if it ever was an instance method but it probably was.我无法从代码中判断它是否曾经是实例方法,但它可能是。
The links you included alternate between .net 4.x and .net core , it's not clear if you are aware of this.您包含的链接在.net 4.x和.net core之间交替,不清楚您是否知道这一点。 Labelling them with dates suggests a linear progression but we have a fork in the road.
用日期标记它们表明线性进展,但我们有一个岔路口。
And that is all, it was 'demoted' to residing in an additional package because it will be used less.仅此而已,它被“降级”为驻留在额外的 package 中,因为它将减少使用。 In .net core we now have similar extensionmethods acting on HttpClient directly.
在 .net 核心中,我们现在有类似的扩展方法直接作用于 HttpClient。
In order to use this with .net core 3.x you may have to add the System.Net.Http.Json
nuget package. In order to use this with .net core 3.x you may have to add the
System.Net.Http.Json
nuget package. The extensions only work with System.Text.Json
, for Newtonsoft you will have to use the traditional code patterns.扩展仅适用于
System.Text.Json
,对于 Newtonsoft,您将不得不使用传统的代码模式。
HttpClientJsonExtensions appears to be absent from .NET Core 3.1 online documentation as of 2020 July.截至 2020 年 7 月,.NET Core 3.1 在线文档中似乎没有 HttpClientJsonExtensions。
The other answers are not correct.其他答案不正确。
The method ReadAsAsync is part of the System.Net.Http.Formatting.dll ReadAsAsync 方法是 System.Net.Http.Formatting.dll 的一部分
Which in turn is part of the nuget: Microsoft.AspNet.WebApi.Client这又是 nuget 的一部分: Microsoft.AspNet.WebApi.Client
I just created a new Console project.Net Core 3.1 and added 2 nugets我刚刚创建了一个新的 Console project.Net Core 3.1 并添加了 2 个 nugets
I created a project with .NET Core 3.1 here are some pictures:我用 .NET Core 3.1 创建了一个项目,这里有一些图片:
Here is my project file:这是我的项目文件:
Here is the code I just wrote which compiles just fine:这是我刚刚编写的代码,编译得很好:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace Custom.ApiClient
{
internal static class WebApiManager
{
//private const string _requestHeaderBearer = "Bearer";
private const string _responseFormat = "application/json";
private static readonly HttpClient _client;
static WebApiManager()
{
// Setup the client.
_client = new HttpClient { BaseAddress = new Uri("api url goes here"), Timeout = new TimeSpan(0, 0, 0, 0, -1) };
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_responseFormat));
// Add the API Bearer token identifier for this application.
//_client.DefaultRequestHeaders.Add(RequestHeaderBearer, ConfigHelper.ApiBearerToken);
}
public static async Task<T> Get<T>()
{
var response = _client.GetAsync("api extra path and query params go here");
return await ProcessResponse<T>(response);
}
private static async Task<T> ProcessResponse<T>(Task<HttpResponseMessage> responseTask)
{
var httpResponse = await responseTask;
if(!httpResponse.IsSuccessStatusCode)
throw new HttpRequestException(httpResponse.ToString());
var dataResult = await httpResponse.Content.ReadAsAsync<T>();
return dataResult;
}
}
}
UPDATE:更新:
To clear some confusion about the dependecies for package Microsoft.AspNet.WebApi.Client清除有关 package Microsoft.AspNet.WebApi.Client 的依赖项的一些混淆
Here is a picture of the dependecies showing as of 2020-10-27 the dependencies which clearly shows it depends on Newtonsoft JSON 10 or higher.这是一张显示截至 2020 年 10 月 27 日的依赖项的图片,这些依赖项清楚地表明它依赖于 Newtonsoft JSON 10 或更高版本。 As of today there is no replacement of ReadAsAsync using System.Text.Json... So you can use ApiClient + Newtonsoft Json or create your own using System.Text.Json
到今天为止,没有使用 System.Text.Json 替换 ReadAsAsync... 所以您可以使用 ApiClient + Newtonsoft Json 或使用 System.Text.ZEED8D85B888A6C0158342408 创建自己的
Something I used recently, I had to install Newtonsoft.Json我最近使用的东西,我必须安装 Newtonsoft.Json
string responseContent = await response.Content.ReadAsStringAsync();
var productResult = JsonConverter.DeserializeObject<Product>(responseContent);
I actually found this in Microsoft documents on how to consume a REST API, and it worked.实际上,我在有关如何使用 REST API 的 Microsoft 文档中发现了这一点,并且它起作用了。 Your code is ok on the get part, assuming it has the right Uri,
你的代码在获取部分没问题,假设它有正确的 Uri,
Also something to not is my code wasn't static还有一点是我的代码不是 static
If you don't want to install third party nuget packages, it's not too difficult to implement an extension method for this.如果您不想安装第三方 nuget 包,为此实现扩展方法并不难。
For example, using System.Text.Json
:例如,使用
System.Text.Json
:
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
public static async Task<T> ReadAsAsync<T>(this HttpContent content) {
string contentString = await content.ReadAsStringAsync();
JsonSerializerOptions options = new JsonSerializerOptions {
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
return (T)JsonSerializer.Deserialize(contentString, typeof(T), options);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.