代码之家  ›  专栏  ›  技术社区  ›  McKay

C#WebRequest成功。NET但使用Mono失败

  •  0
  • McKay  · 技术社区  · 8 年前

    我正在尝试访问web服务器上托管的Rest API。 此服务器具有自签名证书。 因此,出于开发目的,我重写了ServicePointManager的ServerCertificateValidationCallback

    我的程序如下所示:

    class Program
    {
        static void Main(string[] args)
        {
            string BASE_URL = "api-endpoint-addr";
            string param = "some-param";
    
            GetRequest(BASE_URL + param);
            Console.ReadLine();
        }
    
        /**
         * Accept any certificate (for dev purpose)
         */
        private static bool TrustCertificate(object sender, X509Certificate x509Certificate, X509Chain x509Chain, SslPolicyErrors sslPolicyErrors)
        {
            // all Certificates are accepted
            Console.WriteLine("Accepting anyway...");
            return true;
        }
    
        static void GetRequest(string uri)
        {
            ServicePointManager.ServerCertificateValidationCallback = TrustCertificate;
    
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.BeginGetResponse(ResponseCallback, request);
    
        }
    
        static private void ResponseCallback(IAsyncResult result)
        {
            Console.WriteLine("Response CB");
            HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
    
            Console.WriteLine("responseFromServer=" + responseFromServer);
        }
    
    }
    

    当它使用构建此代码时。NET在VisualStudio中一切正常,我可以连接到服务器并获取JSON,但在尝试使用Mono构建它时,从来不会调用TrustCertificate回调(我不知道“无论如何都接受…”在控制台中),程序停止并出现以下错误:

    Unhandled Exception : System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.IO.IOException: unable to read data from the transport connection : an existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: an existing connection was forcibly closed by the remote host
    

    这里有什么问题?我真的不明白为什么Mono失败了

    1 回复  |  直到 8 年前
        1
  •  0
  •   McKay    8 年前

    正在添加

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    

    在GetRequest(uri)开始时,解决了这个问题。

    推荐文章