我正在使用 IHttpClientFactory 使用 Net Core 2.2 从外部 API 发送请求和接收 HTTP 响应。
我已经实现了一个 DelegatingHandler 来“拦截”我的 http 请求并添加授权标头(令牌)。如果令牌无效,它会获取一个新令牌并重试一次。
同样,当我第一次获得新令牌时,我会将令牌缓存在内存中以供进一步参考。为了缓存令牌,我创建了一个需要 accountID 和令牌的字典。
我遇到的问题是 DelegatingHandler 是在 Startup.cs 类中注册的,但是当时我没有 accountID,我在 Controller 的 ActionMethod 中将 accountID 作为参数获取。该操作方法是调用 SendAsync 并从 DelegatingHandler 获取令牌的方法,依此类推。
我不知道,在控制器收到请求后,如何将该 accountID 注入 DelegatingHandler。
我正在尝试创建一个 IClientCredentials 接口和该接口的实现,该接口可以在控制器中实例化并注入到 DelegatingHandler 中。
我的代码如下所示:
委托处理程序:
public class AuthenticationDelegatingHandler : DelegatingHandler
{
private readonly AccessTokenManager _accessTokenManager;
private readonly IClientCredentials _clientCredentials;
public AuthenticationDelegatingHandler(IHttpClientFactory httpClientFactory,
IOptions<AppSettings> appSettings, IClientCredentials clientCredentials)
{
_accessTokenManager = new AccessTokenManager(httpClientFactory, appSettings);
_clientCredentials = clientCredentials;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var clientCredentials = _clientCredentials.GetClientCredentials();
var accessToken = _accessTokenManager.GetToken(clientCredentials._accountID);
if (accessToken == null) {
accessToken = await _accessTokenManager.GetAccessTokenAsync(clientCredentials._accountID);
_accessTokenManager.AddOrUpdateToken(clientCredentials._accountID, accessToken);
}
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.access_token);
var response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
{
var token = await _accessTokenManager.GetAccessTokenAsync(clientCredentials._accountID);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.access_token);
response = await base.SendAsync(request, cancellationToken);
}
return response;
}
}
Startup.cs 像这样:
services.AddScoped<IClientCredentials>(_ => new
ClientCredentials("au","123"));
services.AddHttpClient("myClient")
.AddHttpMessageHandler<AuthenticationDelegatingHandler>();
和控制器:
[HttpPost("{siteName}/{accountID}")]
public async Task<ActionResult<AirRequest>> Post(AirModel model, string
siteName, string accountID)
{
....
SetClientCredentials(siteName, accountID);
var clientJAAPI =
_httpClientFactory.CreateClient("myClient");
var responseclientJAAPI = await
clientJAAPI.SendAsync(request);
.....
}
private ClientCredentials SetClientCredentials(string siteName, string
accountID) =>
new ClientCredentials(siteName, accountID);