1

Getting a error while posting to a external API :Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

try
        {
            ServicePointManager.Expect100Continue = true;
            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 |
            //                                        SecurityProtocolType.Tls |
            //                                        SecurityProtocolType.Tls11 |
            //                                        SecurityProtocolType.Tls12;
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = method;
            webRequest.KeepAlive = true;
            //webRequest.Accept = "*/*";
            //webRequest.ProtocolVersion = HttpVersion.Version10;
            //webRequest.ServicePoint.ConnectionLimit = 1;

            string basicAuthCredentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(CLIENT_ID + ":" + CLIENT_SECRET));
            webRequest.Headers.Add(HttpRequestHeader.Authorization, "Basic " + basicAuthCredentials);
            if (method == "POST")
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(body);
                webRequest.ContentType = "application/json";
                webRequest.ContentLength = byteArray.Length;

                Stream dataStream = webRequest.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
            }

            using (WebResponse webResponse = webRequest.GetResponse())
            {
                HttpStatusCode responseCode = ((HttpWebResponse)webResponse).StatusCode;
                statusCode = responseCode;
                using (StreamReader Reader = new StreamReader(webResponse.GetResponseStream()))
                {
                    responseText = Reader.ReadToEnd();
                    Reader.Close();
                    return responseText;
                }
            }
        }

        catch (WebException e)
        {
            //Response.Write(((HttpWebResponse)e.Response).StatusDescription + "<br/><br/>");
            using (WebResponse response = e.Response)
            {
                HttpWebResponse httpResponse = (HttpWebResponse)response;
                if (httpResponse != null)
                {
                    statusCode = httpResponse.StatusCode;
                    using (Stream data = response.GetResponseStream())
                    using (var reader = new StreamReader(data))
                    {
                        responseText = reader.ReadToEnd();
                        return responseText;
                    }
                }
                else
                {
                    Response.Write("Message: " + e.Message + "<br/><br/>");
                    Response.Write("Source: " + e.Source + "<br/><br/>");
                    Response.Write("StackTrace: " + e.StackTrace + "<br/><br/>");
                    if (e.InnerException != null)
                    {
                        Response.Write("Inner Message: " + e.InnerException.Message + "<br/><br/>");
                        Response.Write("Inner Source: " + e.InnerException.Source + "<br/><br/>");
                        Response.Write("Inner StackTrace: " + e.InnerException.StackTrace + "<br/><br/>");

                    } 
                    return null;
                }
            }
        }
    }

I am getting the error after exceuting the line

Stream dataStream = webRequest.GetRequestStream();

Tried solutions has commented out in the code snippet. I have .NET 4.5 installed on the Server.

Here is my error details :

Message: The underlying connection was closed: An unexpected error occurred on a send.

Source: System

StackTrace: at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) at System.Net.HttpWebRequest.GetRequestStream() at ApiTest.Execute(String url, String method, String body, HttpStatusCode& statusCode) in c:\WebSite\ApiTest.aspx.cs:line 93

Inner Message: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Inner Source: System

Inner StackTrace:

at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) 
at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count) 
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) 
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) 
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) 
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest) 
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult) 
at System.Net.TlsStream.CallProcessAuthentication(Object state) 
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result) at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size) 
at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size) at System.Net.ConnectStream.WriteHeaders(Boolean async)
3

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.