前段时间做了个微信小程序,后端接口需要调用微信的接口拿到用户的openId和手机号,需要调用code2session和getPhoneNumber。在测试环境一切正常,等到了上线以后,噩梦开始了。
交代一下技术栈,后端用的是老古董ASP.NET(.NET Framework 4.5.2)。
由于日志记录的不够清楚只记录了错误的Message,没有太多的有用信息,一度怀疑是用了Result读取响应数据导致了死锁,然后就把Result改成了async/await写法,好消息是错误变了,坏消息是还是有错误。然后又把错误日志详细了一下,就得到了如下的报错。
One or more errors occurred. at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) at CMS.WebApi.Controllers.WX.MPUserInfoController.GetPhoneNumber(String code) An error occurred while sending the request. The underlying connection was closed: An unexpected error occurred on a send. at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) Authentication failed because the remote party has closed the transport stream. at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult) at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
看上去有用的就是Authentication failed because the remote party has closed the transport stream。不过用处也不是很大。不过还是在网上搜到了一些东西,说是ServicePointManager.SecurityProtocol设置成tsl tsl11 tsl2就可以了,听劝。不过后面还是出了问题。一度陷入绝望。
写了两个接口,一个用来查询当前的SecurityProtocol,一个用来修改SecurityProtocol并重新创建用于发请求的HttpClient请求。每次有报错时,通过查询接口返回的是ssl3,然后手动改成tsl tsl11 tsl2 ,然后就又成功了。为了测试,自己手动调用接口改成ssl3,发现竟然又失败了,说明确实是这个问题。不过代码里创建HttpClient时是指定了SecurityProtocol的,全局搜了代码也没地方改这个值,为什么过段时间就变回了ssl3,不得而知。
解决办法就是每次拿全局HttpClient实例时会提前把SecurityProtocol设置一下,保证发请求时该值不是ssl3
问题是解决了,但是再底层的原因却不得而知,有点失落。
如果有帮助请点赞,嘻嘻:)