无法访问HttpClient的DelegatingHandler类中的已处置对象

问题描述 投票:1回答:1

我正在将TokenHttpHandler用于HttpClient。看起来像这样。

public class TokenHttpHandler : DelegatingHandler
  {
    private readonly ITokenCache tokenCache;
    private readonly IHttpProxyClientService proxyClientService;

    public TokenHttpHandler(IHttpProxyClientService proxyClientService, ITokenCache tokenCache)
    {
      this.proxyClientService = proxyClientService;
      this.tokenCache = tokenCache;

      var useProxy = AppSettingsProvider.AppSettings.Proxy.UseProxy;
      InnerHandler = useProxy ? proxyClientService.GetProxyHandler() : new HttpClientHandler();
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
      var response = await SetAuthHeaderAndSendAsync(request, cancellationToken, false).ConfigureAwait(false);
      if (response.StatusCode == HttpStatusCode.Unauthorized)
      {
        response = await SetAuthHeaderAndSendAsync(request, cancellationToken, true);
      }
      return response;
    }

    private async Task<HttpResponseMessage> SetAuthHeaderAndSendAsync(HttpRequestMessage request, CancellationToken cancellationToken, bool forceTokenRefresh)
    {      
      request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await tokenCache.GetAccessToken(forceTokenRefresh).ConfigureAwait(false));
      return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
    }
  }

在使用autofac的ASP.NET核心应用程序中,我注册了类似的类型:

// Token cache
      builder.RegisterType<TokenCache>().As<ITokenCache>()
        .WithParameter("scope", "Scope")
        .SingleInstance();

      builder.RegisterType<TokenHttpHandler>()
        .InstancePerLifetimeScope();

      builder.RegisterType<ProductionHttpClient>()
        .As<HttpClient>()
        .InstancePerLifetimeScope();

问题是因为只有代码才行:

返回等待基地。SendAsync(request,cancelToken).ConfigureAwait(false);

我收到错误:

“无法访问已处置的对象。\ r \ n对象名称:'TokenHttpHandler'。”这是怎么回事?

我在这里想念什么?

.net asp.net-core asp.net-core-2.1
1个回答
0
投票

公共IServiceProvider ConfigureServices(IServiceCollection服务)加载项

services.AddScoped<HttpClient>();
services
   .AddHttpClient<ProductionHttpClient>()
   .AddHttpMessageHandler<TokenHttpHandler>();
© www.soinside.com 2019 - 2024. All rights reserved.