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



我正在尝试访问托管在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);
    }
}

当它在 VisualStudio 中使用 .NET 构建此代码时一切正常,我可以连接到服务器并获取 JSON,但是当尝试使用 Mono 构建它时,永远不会调用信任证书回调(我不是"无论如何接受..."在控制台中(,程序停止并显示以下错误:

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

这里有什么问题?我真的不明白为什么它与单声道失败

添加

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

在GetRequest(uri(的开头解决了这个问题。

最新更新