Search code examples
flurl

I can use SocketHttpHandler instead of HttpMessageHandler?


Flurl is configured by default to use HttpMessageHandler. However, my application uses .NET Core 3.1 and I know that this framework has better support for the new SocketHttpHandler class. So can I create a custom class like this?


public class CustomHttpClientFactory : DefaultHttpClientFactory
{
    #region Overrides of DefaultHttpClientFactory

    /// <summary>
    ///     Override in custom factory to customize the creation of HttpClientHandler used in all Flurl HTTP calls.
    ///     In order not to lose Flurl.Http functionality, it is recommended to call base.CreateMessageHandler and
    ///     customize the result.
    /// </summary>
    public override HttpMessageHandler CreateMessageHandler() => new SocketsHttpHandler
    {
        AllowAutoRedirect           = false,
        ConnectTimeout              = TimeSpan.FromMinutes(1),
        PooledConnectionLifetime    = TimeSpan.FromMinutes(1),
        PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1),
        MaxConnectionsPerServer     = 20,
        SslOptions = new SslClientAuthenticationOptions
        {
            AllowRenegotiation                  = false,
            RemoteCertificateValidationCallback = (sender, certificate, chain, errors) => true
        }
    };

    #endregion
}

And configuration in OnStartup

FlurlHttp.ConfigureClient(AppConstants.ServiceUrl, cli =>
                {
                    cli.BaseUrl = AppConstants.ServiceUrl;

                    cli.Configure(settings =>
                    {
                        settings.ConnectionLeaseTimeout = TimeSpan.FromSeconds(60);
                        settings.Timeout                = TimeSpan.FromSeconds(60);
                        settings.HttpClientFactory      = new CustomHttpClientFactory();
                    }).WithHeaders(headers);
                });

Solution

  • HttpMessageHandler is an abstract class. The implementation used by Flurl by default is HttpClientHandler. I'm guessing that's what you want to swap out for SocketsHttpHandler.

    Fortunately, the .NET team prefers the latter implementation as well, which is why HttpClientHandler now delegates literally all of its work to SocketsHttpHandler.

    In other words, if you're on a platform that supports SocketsHttpHandler (.NET Core 2.1 or greater), you're using it by default. No custom factory is necessary.

    That said, if you need to initialize the handler with some custom configuration, then I think what you've done is fine.