C#:System.Net.WebException:基础连接已关闭

时间:2017-09-08 10:10:51

标签: c# .net rest http

我有以下代码:

String url = // a valid url
String requestXml = File.ReadAllText(filePath);//opens file , reads all text and closes it
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential("DEFAULT\\Admin", "Admin"); 
request.ContentType = "application/xml";
request.ContentLength = bytes.Length;
request.Method = "POST";
request.KeepAlive = false;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
return new StreamReader(responseStream).ReadToEnd();

在运行期间,我在尝试阅读HTTPWebResponse时遇到以下异常:

  

System.Net.WebException:基础连接已关闭:接收时发生意外错误   ---> System.IO.IOException:无法从传输连接读取数据:已建立的连接已被主机中的软件中止。
  ---> System.Net.Sockets.SocketException:已建立的连接已被主机中的软件中止         在System.Net.Sockets.Socket.Receive(Byte []缓冲区,Int32偏移量,Int32大小,SocketFlags socketFlags)
        在System.Net.Sockets.NetworkStream.Read(Byte []缓冲区,Int32偏移量,Int32大小)
        在System.Net.Sockets.NetworkStream.Read(Byte []缓冲区,Int32偏移量,Int32大小)
         在System.Net.PooledStream.Read(Byte []缓冲区,Int32偏移量,Int32大小)
         在System.Net.Connection.SyncRead(HttpWebRequest请求,布尔userRetrievedStream,布尔probeRead)

3 个答案:

答案 0 :(得分:2)

在读取之前不要关闭流。这应该有效:

String url = // a valid url
String requestXml = File.ReadAllText(filePath);//opens file , reads all text and closes it
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential("DEFAULT\\Admin", "Admin"); 
request.ContentType = "application/xml";
request.ContentLength = bytes.Length;
request.Method = "POST";
request.KeepAlive = false;
using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(bytes, 0, bytes.Length);
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        using (Stream responseStream = response.GetResponseStream())
        {
            using (StreamReader streamReader = new StreamReader(responseStream))
            {
                return streamReader.ReadToEnd();
            }
        }
    }
}

答案 1 :(得分:1)

添加这一行代码为我解决了这个问题:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

这取自:https://our.umbraco.com/forum/using-umbraco-and-getting-started/74628-the-underlying-connection-was-closed-an-unexpected-error-occurred-on-a-send

答案 2 :(得分:0)

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(url);
    httpResponse = client.GetAsync(url).Result;
}

试试这个