C# HttpResonseMessage 在 Consoleprogram 中工作,但在具有相同代码的 Forms 或 WPF 中无效

问题描述

我遇到了一个奇怪的问题,当我在 C# 控制台应用程序中尝试此代码时,它会运行并返回一个 json。 但是当我在 WPF 或 Windows Form 上尝试这个时,它没有做任何事情并且卡住了

await client.GetAsync(url);

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var result = test().Result;
            Console.WriteLine(result);
        }

        public static async Task<string> test()
        {
            using var client = new HttpClient();

            client.BaseAddress = new Uri("https://api.bitfinex.com/");
            client.DefaultRequestHeaders.Add("User-Agent","C# console program");
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            var url = "v1/pubticker/adausd";
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessstatusCode();
            var resp = await response.Content.ReadAsstringAsync();

            return resp;
        }
    }
}

解决方法

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

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

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