【问题标题】:SocketException: An existing connection was forcibly closed by the remote hostSocketException:一个现有的连接被远程主机强行关闭
【发布时间】:2019-05-05 01:28:57
【问题描述】:

我有一个调用第 3 方 API 的 Soap 服务。 最近对 api 的调用开始失败。

WebException: The underlying connection was closed: An unexpected error occurred on a send
IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
SocketException: An existing connection was forcibly closed by the remote host

代码是

public static Task<XDocument> PostRtt(Uri uri, string username, string password, XElement requestData)
    {
        var req = (HttpWebRequest)WebRequest.Create(uri);
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";

        var t1 = Task.Factory.FromAsync(req.BeginGetRequestStream, req.EndGetRequestStream, null);
        using (var stream = t1.Result)
       {
        string xmldoc = $"<?xml version=\"1.0\"?>{requestData}";

        var encxml = HttpUtility.UrlEncode(xmldoc);
        string body = $"Username={username}&Password={password}&Version=2&XMLRequest={encxml}";
        var buff = Encoding.UTF8.GetBytes(body);
        stream.Write(buff, 0, buff.Length);
       }
    return Task.Factory.StartNew(() =>
    {
        var t2 = Task.Factory.FromAsync(req.BeginGetResponse, req.EndGetResponse, null);
        using (var resp = t2.Result)
        {
            var wr = (HttpWebResponse)resp;
            if (wr.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("Bad response status code: " + wr.StatusCode);
            }
            using (var rs = wr.GetResponseStream())
            using (var sr = new StreamReader(rs))
            {
                var responseXml = sr.ReadToEnd();
                return XDocument.Parse(responseXml);
            }
        }
    });
  }

我试过了

req.KeepAlive =false

【问题讨论】:

  • 你没有包含测试代码。您是说在一种情况下在 NUnit 下运行相同的测试代码,在另一种情况下在 MS Test 下运行相同的测试代码?还是测试完全不同的代码?无论如何,为了完整起见,请向我们展示失败的测试代码。
  • 我无法再通过测试重现该问题。我已更新问题以删除对测试的提及。

标签: soap httpwebrequest .net-4.7.2


【解决方案1】:

第 3 方已切换到阻止 1.2 以下的 TLS 这个question on updating TLS helped

我必须编辑 web.config 来设置

<httpRuntime targetFramework="4.7.2" />

【讨论】:

    猜你喜欢
    • 2013-06-16
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 2021-05-12
    相关资源
    最近更新 更多