我正在开发.net核心应用程序。我尝试使用IHttpClientFactory来获取HttpClient。我发现有时候某些请求方法GetAsync卡住了。同时,如果我使用新的HttpClient(),它工作正常
网址:
https://i.mycdn.me/image?id=879381309947&t=33&plc=API&aid=1246413312&tkn= * 6UWxsdoE8PBzmpmnySW2C9DI064
这卡住了
HttpClient client = ClientFactory.CreateClient();
client.Timeout = TimeSpan.FromMilliseconds(FileStorageOptions.RequestRemoteImageTimoutMilliseconds);
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode) return await response.Content.ReadAsByteArrayAsync();
return null;
这很好用:
using (var client2 = new HttpClient() { Timeout = TimeSpan.FromMilliseconds(FileStorageOptions.RequestRemoteImageTimoutMilliseconds) })
using (var result = await client2.GetAsync(uri))
{
if (result.IsSuccessStatusCode)
return await result.Content.ReadAsByteArrayAsync();
return null;
}
怎么解决?
我可以在.NET Core控制台应用程序中运行此代码而不会出现问题:
static async Task Main(string[] args)
{
var services = new ServiceCollection().AddHttpClient().BuildServiceProvider();
var clientFactory = services.GetRequiredService<IHttpClientFactory>();
var client = clientFactory.CreateClient();
client.Timeout = TimeSpan.FromSeconds(10);
var response = await client.GetAsync("https://i.mycdn.me/image?id=879381309947&t=33&plc=API&aid=1246413312&tkn=*6UWxsdoE8PBzmpmnySW2C9DI064");
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsByteArrayAsync();
}
}