3

I have a HttpWebRequest that was working, and after a few weeks, it suddenly stopped working and starts to throw an error:

Here is my code:

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

HttpWebRequest FirstRequest = null;
HttpWebRequest postRequest = null;
HttpWebResponse response = null;
try
{
    FirstRequest = (HttpWebRequest)WebRequest.Create("https://my.emerchantpay.com");
    FirstRequest.CookieContainer = new CookieContainer();
    FirstRequest.CookieContainer = _cookies;
    FirstRequest.Accept = @"text/html, application/xhtml+xml, */*";
    FirstRequest.Referer = @"https://my.emerchantpay.com";
    FirstRequest.Headers.Add("Accept-Language", "en-GB");
    FirstRequest.UserAgent = @"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)";
    FirstRequest.Host = @"my.emerchantpay.com";
    response = (HttpWebResponse)FirstRequest.GetResponse();//here is error
}catch{}

What am I doing wrong?

Vladimir Potapov
  • 2,347
  • 7
  • 44
  • 71

2 Answers2

5

After long research i found answer.

You need to add ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
 FirstRequest = (HttpWebRequest)WebRequest.Create("https://my.emerchantpay.com");
                    FirstRequest.CookieContainer = new CookieContainer();
                    FirstRequest.CookieContainer = _cookies;
                    FirstRequest.Accept = @"text/html, application/xhtml+xml, */*";
                    FirstRequest.Referer = @"https://my.emerchantpay.com";
                    FirstRequest.Headers.Add("Accept-Language", "en-GB");
                    FirstRequest.UserAgent = @"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)";
                    FirstRequest.Host = @"my.emerchantpay.com";

                    response = (HttpWebResponse)FirstRequest.GetResponse();
Vladimir Potapov
  • 2,347
  • 7
  • 44
  • 71
  • +1 In .NET 4.0 (where `SecurityProtocolType.Tls12` is missing) you need to use `(SecurityProtocolType) 0xc00` - see https://stackoverflow.com/a/51346252/47528 – Dan Nov 15 '18 at 11:24
0

After adding both ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

and

FirstRequest.Keepalive = false;

worked for me