c# - 如何使用 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>();
这实现了IHttpClientFactory
向DelegationAuthServiceClient
提供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
什么?
解决方案
推荐阅读
- javascript - TranslateX 每一个transitionend
- java - html页面拒绝应用样式bootstrap.min.css
- python - django.core.exceptions.ImproperlyConfigured:无法导入 ASGI_APPLICATION 模块“project.routing”
- wordpress - Demo的默认主页不能被覆盖
- keras - 验证步骤很冗长
- android - 密码可见性切换android没有textinputlayout
- sql - 在我的情况下,为什么 SQL Server 中的周转换失败?
- mysql - 如何设计具有动态列的关系数据库?
- variable-assignment - 真的将参数绑定到参数吗?(Perl6)
- c# - 如果您刚刚获得 ClientId 和 ClientSecret 并且没有刷新令牌,那么为 API 更新访问令牌的最佳做法是什么?