Switching from HttpClientHandler to SocketsHttpHandler
tswiftma
Posted on February 18, 2021
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);
}
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);
}
It was very hard to find this example anywhere so I hope you can use it when you have to!
Posted on February 18, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.