簡體   English   中英

使用HttpWebRequest在C#中的request.GetResponse()期間身份驗證失敗

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

我正在使用C#、. Net Framework 4.0並嘗試對Http Basic身份驗證執行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中嘗試了所有引用:

身份驗證失敗,因為從Web服務獲得響應時,遠程方已關閉傳輸流異常

帶有內部異常的HttpWebrequest失敗身份驗證失敗,因為遠程方已關閉傳輸流

但是沒有用,仍然會出現同樣的錯誤。 我的代碼有問題嗎?

如下更改ServicePointManager.SecurityProtocol后,此問題得以解決:

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

由於Tls 1.1、1.2在.net Framework 4.0中無法直接在System.Net中使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM