3

我正在尝试在 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# 中工作?谢谢!

4

1 回答 1

2

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

我的问题是我需要如下声明一个 SSL3 连接

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

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

于 2013-09-13T21:06:46.270 回答