0

I have a Soap service that makes calls to a 3rd party API. Recently calls to the api started failing.

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

The code is

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);
            }
        }
    });
  }

I have tried

req.KeepAlive =false
Kirsten
  • 15,730
  • 41
  • 179
  • 318
  • 1
    You don't include the test code. Are you saying that you are running the same test code under NUnit in one case and under MS Test in another case? Or are the tests completely different code? In any case, to be complete, show us the test code that fails. – Charlie May 05 '19 at 06:52
  • I can no longer reproduce the issue with the tests. I have updated the question to remove mention of the tests. – Kirsten May 06 '19 at 04:22

1 Answers1

0

The 3rd party had switched to blocking TLS below 1.2 This question on updating TLS helped

I had to edit web.config to set

<httpRuntime targetFramework="4.7.2" />
Kirsten
  • 15,730
  • 41
  • 179
  • 318