C#WebRequest使用.NET完成但未能使用Mono

时间:2018-03-21 14:40:42

标签: .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构建它时,永远不会调用TrustCertificate回调(我不是“Acceptiong” ...“在控制台中”,程序因以下错误而停止:

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 个答案:

答案 0 :(得分:0)

添加

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

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