C# 控制台:System.Net.WebException:底层连接已关闭:

问题描述

我正在尝试从 c# 控制台应用程序调用 httpWebRequest。不断获得 System.Net.WebException: The underlying connection was closed:。我搜索了 Stackoverflow 的问题,谷歌没有帮助我。

如果我将 url 粘贴到浏览器上,它可以正常工作并返回 json 文件,但从代码中它无法正常工作。代码中有什么操作吗?

     Console.WriteLine("url: " + url);
        string urlGlobal = url + email;
        urlGlobal = urlGlobal + "?optout_value=0";
        Console.WriteLine("urlGlobal: " + urlGlobal);
        request = (HttpWebRequest)WebRequest.Create(urlGlobal);
        Console.WriteLine("After WebRequest.Create");
        request.Method = "GET";
        request.ContentType = "application/json";
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

        Console.WriteLine("After TLS");
        response = request.GetResponse();

例外:

    Unhandled Exception: System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.ComponentModel
server cannot communicate,because they do not possess a common algorithm
   at System.Net.sspIWrapper.AcquireCredentialsHandle(sspIInterface SecModule,String package,CredentialUse intent,SecureCredential scc)
   at System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse credUsage,SecureCredential& secureCredential)
   at System.Net.Security.SecureChannel.AcquireClientCredentials(Byte[]& thumbPrint)
   at System.Net.Security.SecureChannel.Generatetoken(Byte[] input,Int32 offset,Int32 count,Byte[]& output)
   at System.Net.Security.SecureChannel.NextMessage(Byte[] incoming,Int32 count)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming,AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst,Byte[] buffer,AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Net.Tlsstream.CallProcessAuthentication(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,Object state)
   at System.Net.Tlsstream.ProcessAuthentication(LazyAsyncResult result)
   at System.Net.Tlsstream.Write(Byte[] buffer,Int32 size)
   at System.Net.PooledStream.Write(Byte[] buffer,Int32 size)
   at System.Net.ConnectStream.WriteHeaders(Boolean async)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.GetResponse()

解决方法

您的异常消息的一部分似乎丢失了,但我找到了 this article that might help you.

此类错误消息通常发生在网站无法匹配其他端点可用的加密协议时

它规定了您可以遵循的几个步骤来尝试解决此问题。希望它能解决您的问题。

您必须根据机器上的 .NET 版本和其他依赖项来优化这些步骤。