SocketException:现有连接被远程主机强行关闭

时间:2019-05-05 01:28:57

标签: soap httpwebrequest .net-4.7.2

我有一个Soap服务,可以调用第三方API。 最近对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

1 个答案:

答案 0 :(得分:0)

第三方已切换为阻止TLS低于1.2 此question on updating TLS helped

我必须编辑web.config才能设置

<httpRuntime targetFramework="4.7.2" />