0

我正在开发.net 核心应用程序。我尝试使用 IHttpClientFactory 来获取 HttpClient。我发现有时对于某些请求方法 GetAsync 卡住了。同时,如果我使用 new 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;
                }

如何解决?

4

1 回答 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();
    }
}
于 2019-03-15T02:33:28.343 回答