System.Net.WebException:请求已中止:无法创建SSL / TLS安全通道

时间:2017-09-25 05:31:47

标签: c# wcf ssl

我使用以下代码从我的WCF Web服务发送推送通知

using (var wc = new WebClient())
{
    wc.Headers.Add("Authorization", "Key=" + ConfigurationSettings.AppSettings["apiKey"]);
    var nameValues = new NameValueCollection
    {
        {"registration_id", objSendNotificationBE.RegistrationID},
        {"collapse_key", Guid.NewGuid().ToString()},
        {"data.payload", objSendNotificationBE.Message}
    };
    var resp = wc.UploadValues("https://android.googleapis.com/gcm/send", nameValues);
    respMessage = Encoding.Default.GetString(resp);
    if (respMessage == "Error=InvalidRegistration")
    {
        string respMessage = "";
    }
}

它工作正常但有时我得到例外

System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
   at System.Net.WebClient.UploadValues(Uri address, String method, NameValueCollection data)
   at System.Net.WebClient.UploadValues(String address, NameValueCollection data)

我已在azure服务器上部署了我的Web服务。

1 个答案:

答案 0 :(得分:1)

您正在向使用SSL / TLS的网站发送请求,即以https开头。与您在评论中提到的一样,您需要将Web客户端配置为使用SSL / TLS。您需要弄清楚您尝试访问的远程服务器是使用SSL还是TLS,然后使用正确的安全模式。

您可以在this question.

中看到此答案
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

class Program
{
    static void Main(string[] args)
    {
        Uri address = new Uri("https://archive.org/details/OTRR_In_The_Name_Of_The_Law_Singles");

        ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 ;

        using (WebClient webClient = new WebClient())
        {
            var stream = webClient.OpenRead(address);
            using (StreamReader sr =new StreamReader(stream))
            {
                var page = sr.ReadToEnd();
            }
        }
    }

    /// <summary>
    /// Certificate validation callback.
    /// </summary>
    private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
    {
        // If the certificate is a valid, signed certificate, return true.
        if (error == System.Net.Security.SslPolicyErrors.None)
        {
            return true;
        }

        Console.WriteLine("X509Certificate [{0}] Policy Error: '{1}'",
            cert.Subject,
            error.ToString());

        return false;
    }
}