ClientFactory http客户端请求卡住了

问题描述 投票:0回答:1

我正在开发.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 asp.net-core httpclient httpclientfactory
1个回答
0
投票

我可以在.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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.