Trevor Forentz
Trevor Forentz

Reputation: 147

HTTPS POST in C# to server with bad cert - timeout

I am trying to do a HTTPS POST in C# to a server which does not have a proper SSL certificate installed (my test development server). The request is timing out using WebClient, as well as HttpWebRequest. I've set up my own ServerCertificateValidationCallback to bypass the cert check, but that hasn't helped. If I make the exact same call in a webpage, that call succeeds.

So:

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

My code for the WebClient post is as follows:

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());
    }
}

Any ideas how to get the POST to work in C#? Thanks!

Upvotes: 3

Views: 1599

Answers (1)

Trevor Forentz
Trevor Forentz

Reputation: 147

After more searching, I found someone who was having a similar problem and who had found a solution. To debug this and similar situations, enable SSL tracing/logging as described here. http://blogs.msdn.com/b/dgorti/archive/2005/09/18/471003.aspx

My problem was that I needed to declare an SSL3 connection as follows

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

Adding this to my code before calling client.UploadData fixed the problem.

Upvotes: 2

Related Questions