首页 > 解决方案 > 如何使用 HttpClient 和 Task.WhenAll 避免 ThrowAddingDuplicateWithKeyArgumentException

问题描述

所以,我写了一个类来实现 IdentityServer4 的授权。该类期望HttpClient,IHttpContextAccessor用于访问当前标题和一些设置。

public DelegationAuthServiceClient(HttpClient httpClient, IHttpContextAccessor httpContextAccessor, IIdentityServerSettings identityServerSettings)

在调用 sub-api 之前,我让它请求一个具有必要范围的新令牌。如果没有错误,它会调用:

_httpClient.SetBearerToken(tokenResponse.AccessToken);

Startup.cs使用此委托授予类的 api 中,我有:

services.AddHttpClient<IDelegationAuthServiceClient, DelegationAuthServiceClient>();

这实现了IHttpClientFactoryDelegationAuthServiceClient提供HttpClient.

这一切都很好,直到我尝试Task.WhenAll在重负载下使用多个委托调用。然后,我开始看到:

ThrowAddingDuplicateWithKeyArgumentException
An item with the same key has already been added. Key: System.Net.Http.Headers.HeaderDescriptor

SetBearerToken线。我认为发生这种情况是因为一个委托调用未完成,而另一个正在尝试设置令牌,并且标头中已经存在“Bearer”。

我读过一些文章,讨论为什么HttpClient每次通话都 new up an 不好,而拥有一个 singleton 也不好HttpClient。我认为IHttpClientFactory创建它是为了在必要时处理更新。但是,它看起来并不这样做。

除了不使用之外,避免此错误的建议或正确方法是Task.WhenAll什么?

标签: c#http-headersidentityserver4dotnet-httpclientihttpclientfactory

解决方案


推荐阅读