Using DelegationHandler for HTTP Requests

sonal khatri 51 Reputation points
2024-01-30T11:19:49.0166667+00:00

Hi, I have a requirement to use a DelegationHandler. I have a ServiceA class and an AuthHandler class that inherits from the DelegationHandler class. I created a RestClient class which has an HTTPClient injected, and in this class, I have the common logic to call HttpClient methods, set queryParameters, set headers, etc. My ServiceA class is injecting the RestClient class and, in turn, calls RestClient methods, which, in turn, make all the HTTP requests. I have implemented it like this as I want to keep a generic RestClient class so that all my services, like ServiceA, ServiceB, can call this class, and I do not need to repeat common code. But if I follow this approach, then I am not able to use the DelegationHandler, and it is not invoked. Can you suggest a way?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,731 Reputation points
    2024-01-30T17:17:53.67+00:00

    as the HttpClientFactory implements the delegate pipeline for httpclient, instead of injecting HttpClient, you should inject HttpClientFactory, or use named or typed HttpClients (which implicitly use the factory).

    https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-8.0#consumption-patterns

    0 comments No comments