【发布时间】: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);
}
}
}
【问题讨论】:
-
任何网址。我有同样的行为
-
可能是因为你有 2 个等待在那里?
-
HttpClientRequestAsync().GetAwaiter().GetResult();是你的问题,这会死锁 -
请注意,您可以使用 async Task Main 作为示例。
标签: c# amazon-ec2 .net-core async-await dotnet-httpclient