【问题标题】:'ServicePointManager.FindServicePoint(Uri)' is obsolete: Use HttpClient instead\'ServicePointManager.FindServicePoint(Uri)\' 已过时:改用 HttpClient
【发布时间】:2023-01-09 11:10:21
【问题描述】:

更新从 NET 5 升级到 6 的 C# 后开始出现此错误-

警告 SYSLIB0014“ServicePointManager.FindServicePoint(Uri)”已过时:“WebRequest、HttpWebRequest、ServicePoint 和 WebClient 已过时。请改用 HttpClient。'

var servicePoint = ServicePointManager.FindServicePoint(requestUri.GetEndpoint());
            if (servicePoint.ConnectionLeaseTimeout == -1){}

【问题讨论】:

    标签: httpclient c#-6.0 servicepointmanager


    【解决方案1】:

    Breaking changes in .NET 6Networking 上有 WebRequest, WebClient, and ServicePoint are obsolete

    WebRequest、WebClient 和 ServicePoint 已过时

    外部参照:System.Net.WebRequest、外部参照:System.Net.WebClient 和外部参照:System.Net.ServicePoint 类标记为已过时,并在编译时生成 SYSLIB0014 警告。

    版本介绍

    6.0

    变更说明

    WebRequest、WebClient 和 ServicePoint 类已添加到 2.0 版的 .NET Core 中以实现向后兼容性。但是,他们引入了几个运行时中断更改,例如,WebRequest.GetRequestStream 为整个响应分配内存,WebClient.CancelAsync 并不总是立即取消。

    从 .NET 6 开始,WebRequest、WebClient 和 ServicePoint 类已弃用。这些类仍然可用,但不建议将它们用于新开发。为了减少分析器警告的数量,只有构造方法用 ObsoleteAttribute 属性修饰。

    建议操作

    请改用 System.Net.Http.HttpClient 类。

    对于FTP,由于HttpClient不支持,建议使用第三方库。

    受影响的 API

    • 网络请求
    • HttpWebRequest
    • FtpWebRequest
    • 网络客户端
    • 服务点

    【讨论】:

    • 它只是说改用 HttpClient 类,仅此而已。还需要发生什么?
    • @NovaDev 是为了什么?
    • 他们说使用 HttpClient,但没有具体说明。比如之前有这么一句:servicePoint.UseNagleAlgorithm = false; HttpClient 中的替代方案是什么?
    • 从 5.0 到 6.0 有什么变化?所有版本的源代码都可以在github.com/dotnet/runtime 获得。您只需要选择您想要的标签。
    【解决方案2】:

    我们可以将ServicePointManager.FindServicePoint替换为SocketsHttpHandler,例如:

    在 .NET 框架中

    httpClient = new HttpClient();
    ServicePointManager.FindServicePoint(new Uri(_baseAddress)).ConnectionLeaseTimeout = 5 * 60 * 1000;
    

    在 .NET 核心中

            var socketsHttpHandler = new SocketsHttpHandler()
            {
                PooledConnectionLifetime = TimeSpan.FromMinutes(5),
            };
    
            httpClient = new HttpClient(socketsHttpHandler)
            {
                BaseAddress = new Uri(_baseAddress)
            };
    

    详细可以看看这篇文章:https://makolyte.com/csharp-configuring-how-long-an-httpclient-connection-will-stay-open/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-04
      • 1970-01-01
      相关资源
      最近更新 更多