DEV Community

loading...
Cover image for Switching from HttpClientHandler to SocketsHttpHandler

Switching from HttpClientHandler to SocketsHttpHandler

tswiftma
Software automation guy to pay for my mountain biking equipment. Read some of my Dev.to blog entries on Automation, XUnit, dotnet, Azure!
Updated on ・1 min read

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!

Discussion (0)