Httpclient在.net core3.1上成功运行,但更新到.net 5中连接超时(System.Net.Sockets.SocketException (10060)) C#

前言:

项目本来是在.net core 3.0 版本上跑然后看了看现在都到5.0马上6.0了想着升级一下体验一下新版本的高性能(狗头)然后在测试的时候发现项目里一些请求外部API出现大批请求超时错误如下。没想到刚升级就出岔子了,使用同样的代码在本地运行,环境一致的情况下,将SDK换成.net core 3.0 请求正常,切换到5.0时就开始请求连接超时,没办法先百度看看有没有病友,结果发现就我一个病友,哎,本来有的话就不想发了 ,但是看到没有有用的结果,我还是把我搜索到的一些结果分享给广大病友,希望能有一点帮助把!

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
      System.Net.Http.HttpRequestException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (api.map.baidu.com:80)
       ---> System.Net.Sockets.SocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
         at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
         at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
         at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|283_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.DefaultConnectAsync(SocketsHttpConnectionContext context, CancellationToken cancellationToken)
         at System.Net.Http.ConnectHelper.ConnectAsync(Func`3 callback, DnsEndPoint endPoint, HttpRequestMessage requestMessage, CancellationToken cancellationToken)
         --- End of inner exception stack trace ---
       

 

回归正言,通过错误我们可以发现是在连接上出现了问题,那么最有可能就是tcp握手期间没有得到任何响应,然后我又对我本地端口进行查看,发现都是正常的没有问题,然后在github的.net rutime 项目的Issues中发现这个问题还是有很多人出现的。在查看了一些回复后可以确定问题是由于.net 5中切换到了双协议栈,TcpClient将默认为IPV6,这意味这IPV6将用于IPV4和IPV6的请求,这个时候如果你的客户端或者网络不支持IPV6或双协议栈,连接将会出现超时。   ==>Httpclient perfectly work on 3.1 but timeout in .net 5

 

IPv6 测试 (test-ipv6.com) 这个网址可以测试你当前网络是否支持IPV6连接,这个测试结果似乎没什么用,后来我回家测试也发现显示的也是同样的报告,但是在家使用同样的代码连接都没问题,那么最有可能是公司vpn网络的原因。

 

解决方案和后续

(下方截图原地址 https://github.com/dotnet/runtime/issues/44686 )

这个问题的解决方案,net runtime团队给出了原因和建议,大概的意思根本原因是由于3.0升级到5.0之后,HttpClient使用双栈套接字所造成的

相关代码

 

 

 

 

同时此问题已经添加到.net 6.0 里程碑(https://github.com/dotnet/runtime/issues/47267中希望在6.0能够完美解决这个问题。

 

一个系统最重要的还是稳定性,不能一味的追求新版本和高性能,还好是在本地测试的时候就发现了不然代码和人总得跑一个(狗头保命),病友们,稳住别浪!!!。

 

不怎么会写文章如果当中有错误也欢迎大家指正!最后老老实实把5.0切换到3.0,等到6.0在看看把。

 相同问题

https://github.com/dotnet/runtime/issues/52287

https://github.com/dotnet/runtime/issues/47267

https://github.com/dotnet/runtime/issues/47583

 关于httpclient HttpClient 连接池在.NET核心-史蒂夫戈登-代码与史蒂夫 (stevejgordon.co.uk)

posted @ 2021-06-24 00:19  不会敲代码的蒋大帅哥  阅读(1191)  评论(0编辑  收藏  举报