【问题标题】:Web request from HttpClient stuck来自 HttpClient 的 Web 请求卡住
【发布时间】:2019-08-06 12:42:44
【问题描述】:

我使用 HttpClient 类创建了 http 请求。我想向某个 url 发出 GET 请求。例如“http://www.google.com”或其他网址。

我的应用程序托管在 Amazon EC2 中并使用 .Net Core 2.2。

    static HttpClient client = new HttpClient();

    private static async Task HttpClientRequestAsync(string url)
    {
        try
        {
            var response = await client.GetAsync(url);

            string responseJson = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseJson);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

我不知道为什么,但我的请求停留在 client.GetAsync 中。之后什么都没有发生,没有任何响应或异常。这很奇怪,因为我只能在 Amazon EC2 实例上看到这种行为。在我的本地机器上,这个请求成功运行。当我在 EC2 机器上使用 Postman 或 Chrome 并创建相同的请求时 - 我收到了响应。如果我将 HttpClient 替换为 WebRequest - 我有相同的行为。

提前谢谢你

控制台应用程序的最小可重现示例:

class Program
{
    static void Main(string[] args)
    {
        HttpClientRequestAsync().GetAwaiter().GetResult();

        Console.ReadLine();
    }

    static HttpClient client = new HttpClient();

    private static async Task HttpClientRequestAsync()
    {
        try
        {
            Console.WriteLine("Your url:");
            var url = Console.ReadLine();

            var response = await client.GetAsync(url);
            string responseJson = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseJson);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

【问题讨论】:

标签: c# amazon-ec2 .net-core async-await dotnet-httpclient


【解决方案1】:

代替

HttpClientRequestAsync().GetAwaiter().GetResult();

使用这个:

Task.Run(async () => await HttpClientRequestAsync());

【讨论】:

    【解决方案2】:

    创建 HttpClient 时禁用代理对我有帮助: 使用代理 = 假; 代理 = null;

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      相关资源
      最近更新 更多