Search code examples
c#.netdotnet-httpclient

Somehow Microsoft is using protected method from SocketsHttpHandler but I can't


I'm trying to create derived class from HttpMessageHandler exactly like it was done here. I stumbled right in the beginning, my code so far:

public class InternetClientHandler : HttpMessageHandler
    {
        private readonly SocketsHttpHandler _socketsHttpHandler;

        public InternetClientHandler()
        {
            _socketsHttpHandler = new SocketsHttpHandler();
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            return _socketsHttpHandler.SendAsync(request, cancellationToken); //ERROR
        }
    }

This is an exact copy of Microsoft's implementation of HttpClientHandler but method _socketsHttpHandler.SendAsync doesn't compile because SendAsync of SocketsHttpHandler is protected. Why it works in MS's code but not in mine? Is it some sort of extension method? If so then why Intelli Sense doesn't provide help to insert the right using?


Solution

  • You can't access SocketsHttpHandler.SendAsync because it is marked as protected internal. This means you either need to be in the same assembly (ie Microsoft's code), or you need to inherit from it. And you can't inherit because it's marked as sealed.

    Instead, you should inherit from DelegatingHandler, which is part of the same assembly and therefore able to call it. This was designed for exactly this scenario.

    public class InternetClientHandler : DelegatingHandler
    {
        public InternetClientHandler() : base(new SocketsHttpHandler())
        {
            // change InnerHandler properties here
        }
    
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // do stuff
            return await base.SendAsync(request, cancellationToken); // will call InnerHandler.SendAsync
        }
    }