如何在DelegatingHandler中读取发送到操作方法(WebAPI)的参数

时间:2019-06-05 08:38:30

标签: c# asp.net-core dependency-injection token httpclientfactory

我正在使用IHttpClientFactory通过Net Core 2.2从外部API发送请求和接收HTTP响应。

我已经实现了DelegatingHandler来“拦截”我的http请求并添加Authorization标头(令牌)。如果令牌无效,它将获取一个新令牌,然后重试一次。

同样,当我第一次获得新令牌时,我将令牌缓存在内存中以供进一步参考。为了缓存令牌,我创建了一个字典,该字典需要一个accountID和令牌。

我遇到的问题是DelegatingHandler已在Startup.cs类中注册,但是那时我没有accountID,我将accountID作为控制器的ActionMethod中的参数获取。该操作方法是调用SendAsync并从DelegatingHandler等获取令牌的方法。

我不知道,在控制器中收到请求后,如何将那个accountID注入DelegatingHandler中。

我试图创建一个IClientCredentials接口以及该接口的实现,该接口可以在控制器中实例化并注入到DelegatingHandler中。

我的代码如下:

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);

1 个答案:

答案 0 :(得分:0)

您可以使用HttpContext.Items传递数据。 (未经测试,通过手机发送)。 在控制器中:

this.HttpContext.Items["accountId"] = accountId;

在处理程序中注入IHttpContextAccessor

var accountId = _httpContextAccessor.HttpContext.Items["accountId"];

IHttpContextAccessor默认情况下未注册,但可以由您使用的组件之一进行注册。如果遇到异常,请在DI中明确注册它:

services.AddHttpContextAccessor();

如果缺少IHttpContextAccessor类型,请添加Microsoft.AspNetCore.Http nuget。

数据将一直存放在那里,直到请求结束。