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 (3)

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...

Collapse
 
jannavarro profile image
jannavarro

Thanks for mentioning this. I was curious if there was any reason to still use SocketsHttpHandler so I asked a question in the Github repo. James NK mentioned there are still cases when we would want to use it such as setting SocketsHttpHandler.EnableMultipleHttp2Connections. Link to the question: github.com/grpc/grpc-dotnet/issues...

Collapse
 
crossbound profile image
David

One reason I'm using SocketsHttpHandler is to set the PooledConnectionLifetime as is described here: learn.microsoft.com/en-us/dotnet/f...