Fixed the issue the underlying connection was closed: An unexpected error occurred on a receive in net framework 3.5

If using SSL to call with WebRequest with framework 3.5 or lower and Server deactive TLS 1.0 and TLS 1.1. This is cause hapend error the issue the underlying connection was closed: An unexpected error occurred on a receive



How to fix?
In the method request add this code below to solved the problem

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;



public string PostXml(string URL, string param)
        {
            URL = URL + "?" + param;
            try
            {
                System.Net.WebRequest webRequest = System.Net.WebRequest.Create(URL);
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.Method = "POST";
                byte[] bytes = Encoding.ASCII.GetBytes(param);
                System.IO.Stream os = null;
                webRequest.ContentLength = bytes.Length;
                os = webRequest.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);

                System.IO.StreamReader sr = null;
                System.Net.WebResponse webResponse = webRequest.GetResponse();
                if (webResponse == null)
                    return "";
                sr = new System.IO.StreamReader(webResponse.GetResponseStream());
                string result = "";
                result = sr.ReadToEnd().Trim();
                if (sr != null)
                    sr.Close();
                return result;
            }
            catch (TimeoutException ex)
            {
                return "{\"status\":\"103\", \"ErrorMessage\": \"Timeout exception: "+ ex.Message +"\"}";
            }
            catch (Exception ex)
            {
                return "{\"status\":\"104\", \"ErrorMessage\": \"Error occur by exception:  " + ex.Message + "\"}";
            }
        }
Reactions

Post a Comment

0 Comments