无法使用HttpRequest

时间:2017-12-12 16:00:28

标签: .net ssl certificate httprequest protocols

您好我正在尝试对网站执行HttpRequest,当我致电GetRequestStream()时,我不断收到此错误。

我的代码:

        byte[] data = Encoding.ASCII.GetBytes(myJson);
        // Create a request for the URL. 
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            ServicePointManager.Expect100Continue = true;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
          "https://host-address.com:443");
        request.ServerCertificateValidationCallback += (sender, certificate2, chain, sslPolicyErrors) => {
            return true;
        };

        X509Certificate2Collection certificates = new X509Certificate2Collection();
       certificates.Import("C:\\Certs\\MyCertificate.pfx", "myCertPassword", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);

        request.ClientCertificates = certificates;

        request.Method = "POST";
        request.ContentType = "text/json";
        request.ContentLength = data.Length;
        request.UserAgent = "My User Agent";
        request.ProtocolVersion = HttpVersion.Version11;
        request.KeepAlive = true;

        Console.WriteLine("Requesting connection....");
        //The exception is thrown here
        using (Stream stream = request.GetRequestStream()) //Here's where the exception happens
        {

            stream.Write(data, 0, data.Length);
        }

我已经尝试了这个Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback但似乎没有用,也设置委托ServerCertificateValidationCallback总是返回true,但它甚至没有达到那个部分。

这可能是一个密码问题? 因为当我在Chrome浏览器上浏览时,我可以从页面获得响应,但不能使用IE浏览器。

1 个答案:

答案 0 :(得分:0)

我建议遵循:

  1. 在本地下载服务器SSL证书,并检查其对本地受信任根CA的链有效性。
  2. 检查服务器SSL证书信息 https://www.ssllabs.com/ssltest/analyze.html
  3. 确保在哪个应用程序运行的用户帐户信任该根CA(可能我需要全局计算机存储,而不是本地存储)。
  4. 从应用程序尝试简单的GET请求。
  5. 希望这可以让你知道什么是错的。