C#中的HTTPS POST到证书错误的服务器 - 超时

时间:2013-09-11 01:24:45

标签: c# post ssl httpwebrequest webclient

我正在尝试在C#中对没有安装正确SSL证书的服务器(我的测试开发服务器)进行HTTPS POST。请求使用WebClient以及HttpWebRequest超时。我已经设置了自己的ServerCertificateValidationCallback以绕过证书检查,但这没有帮助。如果我在网页中进行完全相同的呼叫,则该呼叫成功。

所以:

Call to URL https://testServer/myAction?myData in webpage - succeeds.
POST to https://testServer/myAction with myData using WebClient - timeout.

我的WebClient帖子代码如下:

private static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    //solve the problem of invalid certificates - accept all as valid
    return true;
}    

public void callPost(object o)
{
    string myData = (string)o;
    try
    {
        Uri uri = new Uri("https://testServer/myAction");
        WebClient client = new WebClient();
        client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        byte[] uploadBytes = Encoding.UTF8.GetBytes(myData);
        ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
        byte[] responseBytes = client.UploadData(uri, "POST", Encoding.UTF8.GetBytes(urlData));
        Console.WriteLine("WebRequest:{0}\n", Encoding.ASCII.GetString(responseBytes));
    }
    catch (Exception e)
    {
        Console.WriteLine("WebRequest Error:{0}\n", e.ToString());
    }
}

如何让POST在C#中运行?谢谢!

1 个答案:

答案 0 :(得分:2)

经过更多搜索,我找到了一个有类似问题并找到解决方案的人。 要调试此情况和类似情况,请按此处所述启用SSL跟踪/日志记录。 http://blogs.msdn.com/b/dgorti/archive/2005/09/18/471003.aspx

我的问题是我需要按如下方式声明SSL3连接

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

在调用client.UploadData之前将其添加到我的代码中解决了问题。