'ServicePointManager.FindServicePoint(Uri)' 已过时:改用 HttpClient



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

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

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

关于中的Breaking更改的网络化。NET 6的WebRequest、WebClient和ServicePoint已经过时:

WebRequest、WebClient和ServicePoint已过时

xref:系统。网WebRequest,xref:系统。网WebClient和xref:System。网ServicePoint类被标记为过时,并在编译时生成SYSLIB0014警告。

引入的版本

6.0

更改说明

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

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

建议的操作

使用系统。网Http。改为HttpClient类。

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

受影响的API

  • WebRequest
  • HttpWebRequest
  • FtpWebRequest
  • Web客户端
  • ServicePoint

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

在。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/

最新更新