DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Switching from HttpClientHandler to SocketsHttpHandler
tswiftma
tswiftma

Posted on • Updated on

Switching from HttpClientHandler to SocketsHttpHandler

While going through a recent code review for my Rest API test automation it was suggested that I switch from using System.Net.HttpClientHandler to System.Net.Http.SocketsHttpHandler.

According to this MS article the advantages include:

1) A significant performance improvement when compared with the previous implementation.
2) The elimination of platform dependencies, which simplifies deployment and servicing.
3) Consistent behavior across all .NET platforms.

The switch seemed pretty easy until I tried to leave certs invalidated for debugging (breakpoints anyone?). It used to easy peasy with HttpClientHandler just being a property of the object:

public static HttpClient CreateHttpClient()
{
    var handler = new HttpClientHandler()
    {
       ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
    };
    return new HttpClient(handler);
}
Enter fullscreen mode Exit fullscreen mode

The SocketsHttpHandler library doesn't have this class object property :(, instead you have create a SslClientAuthenticationOptions object for the SocketsHttpHandler class like so:

public static HttpClient CreateHttpClient()
{
   var sslOptions = new SslClientAuthenticationOptions
   {
      // Leave certs unvalidated for debugging
      RemoteCertificateValidationCallback = delegate { return true; },
   };

   var handler = new SocketsHttpHandler()
   {
      SslOptions = sslOptions,
   };

    return new HttpClient(handler);
}
Enter fullscreen mode Exit fullscreen mode

It was very hard to find this example anywhere so I hope you can use it when you have to!

Top comments (1)

Collapse
joc0de profile image
JoC0de

There is really no reason to use SocketsHttpHandler instead of HttpClientHandler in .Net 5 or 6 because HttpClientHandler simply redirects all calls to a internal SocketsHttpHandler instance. github.com/dotnet/runtime/blob/f51...

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.