从 webClient 更改为 httpClient 时出现 Json 响应错误 WebClient 版本HttpClient 版本

问题描述

这个问题是关于 Convert WebClient to HttpClient 线程的。我正在尝试将 WebClient 转换为 httpClient,但在响应 json 中收到以下错误

未处理的异常。 Newtonsoft.Json.JsonSerializationException:检测到类型为 System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1+AsyncStateMachineBox'1

属性“Task”的自引用循环

请在下面找到我的实现:

WebClient 版本

public static T GetFromApi<T>(string url,WebHeaderCollection headerCollection)
{
    T returnObject;
    using (var client = new WebClient())
    {
        client.UseDefaultCredentials = true;
        if (headerCollection != null)
        {
            client.Headers = headerCollection;
        }
        Stream stream = client.OpenRead(url);
        byte[] byteArray;
        using (var memoryStream = new MemoryStream())
        {
            stream.copyTo(memoryStream);
            byteArray = memoryStream.ToArray();
        }
        returnObject = byteArray.DeSerialize<T>();
    }
}

HttpClient 版本

public static async Task<T> GetFromApi<T>(string url,WebHeaderCollection headerCollection)
{
    T returnObject;
    using (HttpClient client = new HttpClient())
    {
        using (HttpResponseMessage response = await client.GetAsync(url))
        {
            response.EnsureSuccessstatusCode(); // Throw if httpcode is an error
            var resultString = await response.Content.ReadAsstringAsync();
            returnObject = JsonConvert.DeserializeObject<T>(resultString);
        }
    }
}

我不明白 json 的自循环是在哪里创建的,我是 .NET Core 和 C# 的初学者,有人可以帮我吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)