使用 WebClient 呼叫 API,網址是 https ,執行時出現以下錯誤訊息:
此問題是因為預設的 SSL/TLS 版本比較舊,現在許多連接伺服器都有要求需要 TLS 1.2 ,解決方式就是指定使用 TLS 1.2 連接:
註: 在 .NET Framework 3.5 中並沒有 SecurityProtocolType.Tls12 ,建議升級到 4.5.2 或以上
System.Net.WebException: 基礎連接已關閉: 傳送時發生未預期的錯誤。 ---> System.IO.IOException: 收到來自傳輸資料
流的未預期 EOF 或 0 個位元組。
於 System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
於 System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
於 System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
於 System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRe
quest)
於 System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
於 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
於 System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
於 System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
於 System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
於 System.Net.ConnectStream.WriteHeaders(Boolean async)
--- 內部例外狀況堆疊追蹤的結尾 ---
於 System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request)
於 System.Net.WebClient.UploadData(Uri address, String method, Byte[] data)
於 ConsoleApplicationApiTest.Service.ApiService.WsZ01A001() 於 C:\Users\ruyut\Documents\RiderProjects\2023\Test\C
onsoleApplication\ApiTest\ConsoleApplicationApiTest\Service\ApiService.cs: 行 39
PS C:\Users\arestccmis2\Desktop\Debug>
此問題是因為預設的 SSL/TLS 版本比較舊,現在許多連接伺服器都有要求需要 TLS 1.2 ,解決方式就是指定使用 TLS 1.2 連接:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
註: 在 .NET Framework 3.5 中並沒有 SecurityProtocolType.Tls12 ,建議升級到 4.5.2 或以上
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com