![](/img/trans.png)
[英]Get custom validation error message from Web Api request to HttpClient
[英]Web request from HttpClient stuck
我用 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);
}
}
}
代替
HttpClientRequestAsync().GetAwaiter().GetResult();
用這個:
Task.Run(async () => await HttpClientRequestAsync());
創建 HttpClient 時禁用代理對我有幫助:UseProxy = false; 代理 = 空;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.