2017-09-25 290 views
0

我使用下面的代碼從我的WCF Web服務發送推送通知System.Net.WebException:請求已中止:無法創建SSL/TLS安全通道

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服務。

+0

你能正確地格式化你的代碼?目前很難讀取 – dat3450

+0

嘗試添加ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;在使用之前(var wc = new WebClient()) – jitender

+0

親愛的Jitender thanx的回覆,但正如我所提到的,這個問題有時候會不經常發生,我該如何檢查它爲什麼只發生一段時間而不是所有的請求。 – Siddhartha

回答

0

您正在向使用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; 
    } 
} 
+0

我通過添加這兩行來解決此問題ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;但是我不明白爲什麼這個錯誤會在一段時間內發生,而不是我們每次調用Web服務時。 – Siddhartha

相關問題