2015-09-25 191 views
9

我希望你能幫助我。我一直在谷歌搜索,並嘗試所有我能找到或想到的解決方案。我試圖加載的站點運行TLS1.2,就像我試圖測試的其他幾個站點一樣,以確保它不是TLS1.2問題。其他網站加載正常。C#HttpWebRequest底層連接已關閉:發送時發生意外錯誤

byte[] buffer = Encoding.ASCII.GetBytes(
    "mod=www&ssl=1&dest=account_settings.ws" 
    + "&username=" + username.Replace(" ", "20%") 
    + "&password=" + password.Replace(" ", "20%")); 

ServicePointManager.MaxServicePointIdleTime = 1000; 
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; 

HttpWebRequest WebReq = 
    (HttpWebRequest)WebRequest.Create(
     "https://secure.runescape.com/m=weblogin/login.ws"); 

WebReq.Method = "POST"; 
WebReq.KeepAlive = false; 

WebReq.Referer = 
    "https://secure.runescape.com/m=weblogin/loginform.ws" 
    + "?mod=www&ssl=1&expired=0&dest=account_settings.ws"; 

WebReq.ContentType = "application/x-www-form-urlencoded"; 
WebReq.ContentLength = buffer.Length; 
Stream PostData = WebReq.GetRequestStream(); 
PostData.Write(buffer, 0, buffer.Length); 
PostData.Close(); 
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse(); 
Stream Answer = WebResp.GetResponseStream(); 
StreamReader _Answer = new StreamReader(Answer); 
reply = _Answer.ReadToEnd(); 
curAccount++; 
if (reply.Contains("Login Successful")) 
{ 
    eturn true; 
} 
else 
{ 
    eturn false; 
} 

不管我怎麼努力我不斷收到異常

基礎連接已關閉:上一個發送發生意外的錯誤。

在更多的細節,我發現

驗證失敗,因爲遠程方已關閉傳輸流。

回答

36

在4.0版本的.NET Framework的ServicePointManager.SecurityProtocol只提供two options設置:

  • SSL3:安全套接字層(SSL)3.0的安全協議。
  • TLS:傳輸層安全(TLS)1.0安全協議

框架中SecurityProtocolType枚舉得到了與較新的TLS協議擴展的下一個版本,因此,如果您的應用程序可以使用第4.5版本,你也可以用途:

  • Tls11:指定傳輸層安全(TLS)1.1安全協議
  • Tls12:指定傳輸層安全(TLS)1.2安全協議。

所以,如果你是在.NET 4.5更改訂單

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; 

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 

使得ServicePointManager將創建支持Tls12連接流。

請注意,枚舉值可以作爲標誌,所以你可以結合多種協議與邏輯OR

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | 
             SecurityProtocolType.Tls11 | 
             SecurityProtocolType.Tls12; 

注意
儘量保持協議的數量,您支持儘可能低並與當今的安全標準保持一致。 Ssll3不再被視爲安全,Tls1.0 SecurityProtocolType.Tls的使用率下降。

+1

你可能想要'Tls | Tls11 | Tls12'在大多數情況下。 –

8

我遇到了這個例外,它也與ServicePointManager.SecurityProtocol有關。

對我而言,這是因爲ServicePointManager.SecurityProtocol已被設置爲Tls | Tls11(因爲某些網站應用程序訪問了破損的TLS 1.2)並訪問了TLS 1。僅限2個網站(使用SSLLabs' SSL Report進行測試),失敗。

用於.NET 4.5和更高的一種選擇是讓所有TLS版本:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls 
            | SecurityProtocolType.Tls11 
            | SecurityProtocolType.Tls12; 
0

對於.NET 4用途:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072; 
+4

通常,不要使用[魔術常量](https://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants)。 –

0

代碼WebTestPlugIn

public class Protocols : WebTestPlugin 
{ 

    public override void PreRequest(object sender, PreRequestEventArgs e) 
    { 
     ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 

    } 

} 
相關問題