HttpContent.ReadAsAsync<T>方法在.NET Core中已被取代吗?

问题描述 投票:0回答:5

以下指的是.NET Core应用程序,其依赖关系如下...

Microsoft.NETCore.App
Microsoft.AspNet.WepApi.Client (5.2.7)

Microsoft.com 上有 2017 年 11 月的文档

Call a Web API From a .NET Client (C#)

链接... https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

文档中是 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;
    }

response.Content
指的是
HttpContent
对象。截至 2020 年 7 月,
HttpContent
没有带有签名
ReadAsAsync<T>()
的实例方法,至少根据以下文档。然而,这个实例方法是有效的。

没有带有签名的实例方法的参考链接

ReadAsAsync<T>()
... https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent?view=netcore-3.1

有一个静态方法

HttpContentExtensions.ReadAsAsync<T>(myContent)
,其中
myContent
指的是
HttpContent
对象。这个静态方法也有效。

参考链接... https://learn.microsoft.com/en-us/previous-versions/aspnet/hh834253(v=vs.118)

例如,一份书面签名具有...

静态图标,后跟

ReadAsAsync<T>(HttpContent)

以及说明它将返回

Task<T>
。这个静态方法可能是实例方法的幕后实现。

但是,静态方法网页顶部有信息表明...... “我们不再定期更新此内容。请检查 Microsoft 产品生命周期,了解有关如何支持此产品、服务、技术或 API 的信息。

实例和静态两种形式的

HttpContent.ReadAsAsync<T>()
是否已在 .NET Core 3.1 中被取代?

c# asp.net-core httpresponse
5个回答
8
投票

其他答案都不正确。

ReadAsAsync 方法是 System.Net.Http.Formatting.dll 的一部分

这又是 nuget 的一部分:Microsoft.AspNet.WebApi.Client

我刚刚创建了一个新的控制台项目 .Net Core 3.1 并添加了 2 个 nugets

  1. 牛顿软件
  2. Microsoft.AspNet.WebApi.Client

我用.NET Core 3.1创建了一个项目,这里有一些图片:

这是我的项目文件:

这是我刚刚编写的代码,编译得很好:

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

更新:

为了消除对 Microsoft.AspNet.WebApi.Client 包的依赖关系的一些困惑

这是一张依赖关系的图片,显示了截至 2020 年 10 月 27 日的依赖关系,清楚地表明它依赖于 Newtonsoft JSON 10 或更高版本。截至今天,还没有使用 System.Text.Json 替代 ReadAsAsync...因此您可以使用 ApiClient + Newtonsoft Json 或使用 System.Text.Json 创建自己的


6
投票

如果你不想安装第三方nuget包,为此实现扩展方法并不太困难。

例如,使用

System.Text.Json
:

using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

public static class HttpContentExtensions {

    private static readonly JsonSerializerOptions defaultOptions = new JsonSerializerOptions {
        PropertyNameCaseInsensitive = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    };

    public static async Task<T> ReadAsAsync<T>(this HttpContent content, JsonSerializerOptions options = null) {
        using(Stream contentStream = await content.ReadAsStreamAsync()) {
            return await JsonSerializer.DeserializeAsync<T>(contentStream, options ?? defaultOptions);
        }
    }

}

3
投票

我无法从代码中判断它是否曾经是一个实例方法,但它可能是。

您包含的链接在 .net 4.x.net core 之间交替,目前尚不清楚您是否意识到这一点。用日期标记它们表明是线性进展,但我们有一个岔路口。

仅此而已,它被“降级”到一个附加包中,因为它的使用量会减少。在.net core中,我们现在有类似的扩展方法直接作用于HttpClient。


为了在 .net core 3.x 中使用它,您可能必须添加

System.Net.Http.Json
nuget 包。这些扩展仅适用于
System.Text.Json
,对于 Newtonsoft,您将必须使用传统的代码模式。


0
投票

我最近使用的东西,我必须安装Newtonsoft.Json

string responseContent = await response.Content.ReadAsStringAsync();
var productResult = JsonConverter.DeserializeObject<Product>(responseContent);

我实际上在 Microsoft 文档中找到了有关如何使用 REST API 的内容,并且它有效。你的代码在获取部分没问题,假设它有正确的 Uri,

还有一点是我的代码不是静态的


0
投票

这对我有用:

response.content.ReadFromJsonAsync<T>()
© www.soinside.com 2019 - 2024. All rights reserved.