【问题标题】:I can use SocketHttpHandler instead of HttpMessageHandler?我可以使用 SocketHttpHandler 代替 HttpMessageHandler 吗?
【发布时间】:2020-05-13 13:04:03
【问题描述】:

Flurl 默认配置为使用 HttpMessageHandler。但是,我的应用程序使用 .NET Core 3.1,我知道这个框架对新的 SocketHttpHandler 类有更好的支持。 那么我可以创建一个这样的自定义类吗?


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
}

以及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);
                });

【问题讨论】:

    标签: flurl


    【解决方案1】:

    HttpMessageHandler 是一个抽象类。 Flurl 默认使用的实现是HttpClientHandler。我猜这就是你想用SocketsHttpHandler 换掉的东西。

    幸运的是,.NET 团队也更喜欢后一种实现,这就是HttpClientHandler now delegates literally all of its work to SocketsHttpHandler 的原因。

    换句话说,如果您在支持SocketsHttpHandler(.NET Core 2.1 或更高版本)的平台上,则默认使用它。不需要自定义工厂。

    也就是说,如果您需要使用一些自定义配置来初始化处理程序,那么我认为您所做的很好。

    【讨论】:

      猜你喜欢
      • 2012-08-11
      • 2022-01-23
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-02
      • 2011-11-08
      相关资源
      最近更新 更多