2015-09-25 189 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; 

    } 

} 
相关问题