文章出處

在網上查了很多資料,基本是這么一個思路:
在通過 HttpWebRequest req
= (HttpWebRequest)HttpWebRequest.Create(url); req.Method = "GET"; HttpWebResponse sp = (HttpWebResponse)req.GetResponse(); 作處理時,有些輸入有些URL會在 HttpWebResponse sp = (HttpWebResponse)req.GetResponse(); 的時候拋出一個“基礎連接已經關閉: 未能為 SSL/TLS 安全通道建立信任關系”的異常。 最簡單的辦法是:
1,先加入命名空間: using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates;
2,再重載CheckValidationResult方法,返回true public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }
3,然后在HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); 前面加上如下幾行代碼: System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; ServicePointManager.ServerCertificatidationCallback = new System.Net.Security.RemoteCertificatidationCallback(CheckValidationResult);//驗證服務器證書回調自動驗證

此時我發現問題可以解決,但是有一個問題是這種方法在在 .net 4.5以上是沒問題的,因為如下:

v4.0

#region 程序集 System.dll, v4.0.0.0
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.dll
#endregion

using System;

namespace System.Net
{
    // 摘要: 
    //     指定 Schannel 安全包支持的安全協議。
    [Flags]
    public enum SecurityProtocolType
    {
        // 摘要: 
        //     指定安全套接字層 (SSL) 3.0 安全協議。
        Ssl3 = 48,
        //
        // 摘要: 
        //     指定傳輸層安全 (TLS) 1.0 安全協議。
        Tls = 192,
    }
}
v4.5
#region 程序集 System.dll, v4.0.0.0
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.dll
#endregion

using System;

namespace System.Net
{
    // 摘要: 
    //     指定 Schannel 安全包支持的安全協議。
    [Flags]
    public enum SecurityProtocolType
    {
        // 摘要: 
        //     指定安全套接字層 (SSL) 3.0 安全協議。
        Ssl3 = 48,
        //
        // 摘要: 
        //     指定傳輸層安全 (TLS) 1.0 安全協議。
        Tls = 192,
        //
        Tls11 = 768,
        //
        Tls12 = 3072,
    }
}

假如在.net 4.0上使用如下代碼時一樣報錯

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;

此時我想在.net 4.0或者以下版本使用上面的方法就不可行,那么怎么辦?

System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
ServicePointManager.ServerCertificatidationCallback = new System.Net.Security.RemoteCertificatidationCallback(CheckValidationResult);//驗證服務器證書回調自動驗證

雖然.net 4.0 SecurityProtocolType 枚舉中沒有 Tls11 和Tls12 兩種類型那么我們只能強轉!!!!!

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜

    大師兄 發表在 痞客邦 留言(0) 人氣()