使用HttpWebRequest在C#中的request.GetResponse()期间身份验证失败

时间:2017-07-26 15:12:09

标签: c# asp.net authentication httpwebrequest httpwebresponse

我正在使用C#,。Net framework 4.0并尝试为Http基本身份验证执行HttpWebRequest并获得以下错误:


Inner Exception 1:
IOException: Authentication failed because the remote party has closed the transport stream.

我正在使用以下代码:


string svcCredentials = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Authorization", "Basic " + svcCredentials);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
    html = reader.ReadToEnd();
}

GetResponse()期间出错。

我在SO中尝试了所有引用:

Authentication failed because the remote party has closed the transport stream exception when getting a response from webservice

Failure on HttpWebrequest with inner exception Authentication failed because the remote party has closed the transport stream

但没有用,仍然得到同样的错误。我的代码中有任何问题吗?

1 个答案:

答案 0 :(得分:0)

在更改ServicePointManager.SecurityProtocol之后解决此问题,如下所示:

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

作为Tls 1.1,1.2直接在System.Net中的.net framework 4.0中不可用。