Search code examples
c#asp.net-coreasp.net-core-webapidotnet-httpclienthttpclientfactory

Attaching httpHandler to httpclientFactory webapi aspnetcore 2.1


I am trying to attach an handler to httpclientfactory using "ConfigurePrimaryHttpMessageHandler"

but when I look inside the HttpClient to see if the handler is there i cannot find it

Am I attaching the handler correctly?

Any Suggesions

     services.AddHttpClient<IGitHubClient,GitHubClient>(client =>
            {
                client.BaseAddress = new Uri(myUri);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            })
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
            {
                AllowAutoRedirect = false,
                AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
            });


    public interface IGitHubClient
    {
        Task<string> GetData();
    }

    public class GitHubClient : IGitHubClient
    {
        private readonly HttpClient _client;

        public GitHubClient(HttpClient httpClient)
        {
            _client = httpClient;
        }

        public async Task<string> GetData()
        {
            return await _client.GetStringAsync("/");
        }
    }

    public class ValuesController : Controller
    {
        private readonly IGitHubClient _gitHubClient;;

        public ValuesController(IGitHubClient gitHubClient)
        {
            _gitHubClient = gitHubClient;
        }

        [HttpGet]
        public async Task<ActionResult> Get()
        {
            //my _gitHubClient has no Handler attached!!!

            string result = await _gitHubClient.GetData();
            return Ok(result);
        }
    }

Solution

  • The code you have shown is the recommend approach.

    The comment about _gitHubClient

    //my _gitHubClient has no Handler attached!!!

    seems like a misunderstanding.

    _gitHubClient is your abstraction that is wrapping a HttpClient instance in its GitHubClient implementation.

    public class GitHubClient : IGitHubClient {
        private readonly HttpClient _client; //<< Handler will be attached to this instance
    
        public GitHubClient(HttpClient httpClient) {
            _client = httpClient;
        }
    
        public async Task<string> GetData() {
            return await _client.GetStringAsync("/");
        }
    }
    

    It is that wrapped instance that would have the attached handler.

    Based on the current configuration, whenever the framework has to create an instance of the IGitHubClient derived GitHubClient for injection, the factory will create a HttpClient using the settings provided at start up. Which would also include adding the HttpClientHandler provided by ConfigurePrimaryHttpMessageHandler