Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host in C#

我与影子孤独终老i 提交于 2019-12-05 12:50:45

The actual exception is probably an IOException - you would need to catch that exception type as well as WebException. The actual problem may be that your URL is out of date and the system is no longer running a web server, or perhaps, the request needs to be authenticated/needs a header as @L.B suggests.

Also, you are potentially leaking all sorts of resources. You should be wrapping your WebResponse and streams in using statements.

using (var response = (HttpWebResponse)request.GetResponse())
using (var receiveStream = response.GetResponseStream())
using (var reader = new StreamReader(receiveStream))
{
     var content = reader.ReadToEnd();
     // parse your content, etc.
}

I had similar problems with the connection being forcibly closed with different hosts. Seems the issue can be resolved by altering various properties of the WebRequest object.

The following findings were outlined in a blog post by briancaos: An existing connection was forcibly closed by the remote host

The steps mentioned in the the above post include:

Set WebRequest.KeepAlive to False.

Set WebRequest.ProtocolVersion to HttpVersion.Version10.

Set WebRequest.ServicePoint.ConnectionLimit to 1

It indeed work for me, but I haven't tested it on multiple hosts as of yet. However, I seriously suggest reading the post as it goes into way more detail.

In case the link get's broken, here's the Archive.org cached version.

Had the same problem today, So I also wrapped the request in a try/catch with WebException, in my case, adding:

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Before the webRequest did the trick. Also you should be wrapping your WebResponse and streams in using statements as tvanfosson mentioned.

I hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!