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

Authentication failed during request.GetResponse() in C# using HttpWebRequest

我正在使用 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();
}
</pre>

GetResponse() 期间出错。

我尝试了 SO 中的所有参考资料:

但是没有用,仍然出现同样的错误。我的代码有问题吗?

更改ServicePointManager.SecurityProtocol后问题解决如下:

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

由于 TLS 1.1、1.2 在 .net framework 4.0 中不可用,直接在 System.Net。