【问题标题】:How to inject an HttpClient CustomDelegatingHandler in dependency injection如何在依赖注入中注入 HttpClient CustomDelegatingHandler
【发布时间】:2023-02-24 16:31:27
【问题描述】:

我有一个用于记录目的的自定义委托处理程序:

    public class LoggingDelegatingHandler : DelegatingHandler {

        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            //my logging
            return await base.SendAsync(request, cancellationToken);
        }
    }

我一直在尝试像这样在我的依赖注入中注入它:

        services.AddHttpClient(nameof(MyAuthorityClient),
                c => { c.BaseAddress = new Uri(myOptions.BaseUri); })
            .AddTransientHttpErrorPolicy(x =>
                x.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt)))
            .ConfigurePrimaryHttpMessageHandler<MyClientHttpHandler>()
            .AddHttpMessageHandler<LoggingDelegatingHandler>();

好像可以编译。但是当执行命中这段代码时:

ar response = await client.GetAsync("/my/api/path");

调试器永远不会到达我的LoggingDelegatingHandler 中的SendAsync 方法。

起初,我以为是因为我正在调用GetAsync,而我的重写方法是SendAsync,但后来我读到它应该仍然命中SendAsync

我究竟做错了什么?

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    试试下面的代码:

    1. 通过创建一个派生自 DelegatingHandler 并覆盖其 SendAsync 方法的新类来定义您的自定义委托处理程序

       public class AuthHeaderHandler : DelegatingHandler
       {
           private readonly string _authToken;
      
           public AuthHeaderHandler(string authToken)
           {
               _authToken = authToken;
           }
      
           protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
           {
               request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _authToken);
               return await base.SendAsync(request, cancellationToken);
           }
       }  
      
    2. 接下来,在服务集合中注册 HttpClient 及其关联的委托处理程序。您可以在启动类的 ConfigureServices 方法中执行此操作。

       public void ConfigureServices(IServiceCollection services)
       {
           // Register the AuthHeaderHandler with the service collection
           services.AddTransient<AuthHeaderHandler>(sp => new AuthHeaderHandler(Configuration["AuthToken"]));
      
           // Register the HttpClient with the AuthHeaderHandler
           services.AddHttpClient("MyHttpClient").AddHttpMessageHandler<AuthHeaderHandler>();
      
           // Add other services and dependencies as needed...
        }
      
    3. 使用构造函数注入将 HttpClient 注入到您的类或服务中。

      public class MyController : Controller
      {
          private readonly HttpClient _httpClient;
          public MyController(IHttpClientFactory httpClientFactory)
          {
              _httpClient = httpClientFactory.CreateClient("MyHttpClient");
          }
      
          // Use the _httpClient instance to send HTTP requests...
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      相关资源
      最近更新 更多