Typed client AddHttpMessageHandler not firing

Holysmokes-6260 41 Reputation points
2021-10-13T06:15:34.433+00:00

Hi all,

I have written a code to customize logging on my http client calls. My DelegatingHandler for http client logging is not firing at all. I suspect the approach of the typed client with my custom delegating handler is a problem. The same code works with named client but the problem is that all my code was written in "typed client style" (code services.AddHttpClient<IMagentoClientService, MagentoClientService > never works). Do I have to renounce that style or I am missing something?

    public class TraceLogHandler : DelegatingHandler
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ILogger<TraceLogHandler> _logger;
        private readonly bool _canLog;
        private StringValues ipAddress;

        public TraceLogHandler(IHttpContextAccessor httpContextAccessor, ILogger<TraceLogHandler> logger)
        {
            _httpContextAccessor = httpContextAccessor;
            _logger = logger;
        }

        public TraceLogHandler(IHttpContextAccessor httpContextAccessor, ILogger<TraceLogHandler> logger, bool canLog)
        {
            _httpContextAccessor = httpContextAccessor;
            _logger = logger;
            _canLog = canLog;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
        //blah blah code for custom logging
        }
    }

In startup.cs

            services.AddTransient<TraceLogHandler>();
            //Inject HttpClient 
            bool canLog = Configuration.GetSection("AppSettings").GetValue<bool>("HttpClientCanLog");


            **services.AddHttpClient<IMagentoClientService, MagentoClientService >().AddHttpMessageHandler((services) =>
            {
                return new TraceLogHandler(services.GetRequiredService<IHttpContextAccessor>(),
                                                services.GetRequiredService<ILogger<TraceLogHandler>>(), canLog);**
            });

Thanks,
Holy

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,254 questions
0 comments No comments
{count} votes

Accepted answer
  1. Brando Zhang-MSFT 3,116 Reputation points Microsoft Vendor
    2021-10-14T03:11:32.99+00:00

    Hi @Holysmokes-6260 ,

    Could you please share the MagentoClientService related codes and how you call the MagentoClientService? I have created a test demo and it works well on my side.

    Below is my test demo codes:

    Client service:

        public class CountryRepositoryClientV2 : ICountryRepositoryClient  
        {  
            private readonly HttpClient _client;  
            private readonly ILogger<CountryRepositoryClientV2> _logger;  
      
      
            public CountryRepositoryClientV2(HttpClient client, ILogger<CountryRepositoryClientV2> logger)  
            {  
                _client = client;  
                _logger = logger;  
            }  
      
      
            public async Task<string> GetAsync()  
            {  
                using (HttpResponseMessage response = await _client.GetAsync("/api/democrud"))  
                {  
                    try  
                    {  
                        return await response.Content.ReadAsStringAsync();  
                    }  
                    catch (Exception e)  
                    {  
                        _logger.LogError(e, "Failed to read content");  
                        return null;  
                    }  
                }     
            }  
        }  
    

    Startup.cs:

                services.AddHttpClient<ICountryRepositoryClient, CountryRepositoryClientV2>()  
            .ConfigureHttpClient(c => c.BaseAddress = new Uri("https://localhost"))  
          .AddHttpMessageHandler((services) =>  
          {  
              return new TraceLogHandler(services.GetRequiredService<IHttpContextAccessor>(),  
                                              services.GetRequiredService<ILogger<TraceLogHandler>>());  
                 });  
    

    I used it inside the home controller:

        public class HomeController : Controller  
        {  
            private readonly ILogger<HomeController> _logger;  
            private readonly IHttpContextAccessor ihttpcontextaccessor;  
            private readonly ICountryRepositoryClient countryRepositoryClient;  
      
            public HomeController(ILogger<HomeController> logger, IHttpContextAccessor _ihttpcontextaccessor, ICountryRepositoryClient _countryRepositoryClient)  
            {  
                _logger = logger;  
                _ihttpcontextaccessor = ihttpcontextaccessor;  
                countryRepositoryClient = _countryRepositoryClient;  
            }  
      
            public async Task<IActionResult> IndexAsync()  
            {  
      
                await  countryRepositoryClient.GetAsync();  
                //HttpContext.Session.SetString("IsLogin", "true");  
      
                return View(new PatientModel { statusOfPatient=1 });  
            }  
    

    Result:

    You could find the breakpoint has been fired:

    egQiL.png

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful