0

I use this code in my .Net Core application to ignore SSL connection exception:

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.MaxServicePointIdleTime = 0;

Problem is it doesn't work on first or second run and it works fine after that until application gets idle again. If application gets idle, first or second run fails again.

Here is full code:

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.MaxServicePointIdleTime = 0;

using (var client = new WebClient())
{
    try
    {
        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        string response = client.UploadString(URL, "POST", $"username={Username}&password={Password}");
    }
    catch (WebException ex)
    {
        if (ex.Response != null)
            ErrorMessage = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();

        ErrorMessage = ex.Message;
    }
}

Error message:

The SSL connection could not be established, see inner exception.

Masoud Keshavarz
  • 2,166
  • 9
  • 36
  • 48
  • Please share a [mcve] – mjwills Jul 14 '21 at 05:45
  • @mjwills Unfortunately I have no idea how to reproduce the error message. It doesn't appears in my other projects at all. It only appears in this particular product machine when application gets idle or if I restart it manually. And some times it doesn't show error message at all even if I restart the application. All this unexpected behaviors made me confused about the origin of the problem. – Masoud Keshavarz Jul 14 '21 at 06:06
  • What application is going idle? The client, or the server it is talking to? – mjwills Jul 14 '21 at 06:14
  • @mjwills The .Net Core application which is hosted on IIS (the server) – Masoud Keshavarz Jul 14 '21 at 06:15
  • Well in that case the SSL mention in the error is likely a red herring. The real issue is the server didn't respond. – mjwills Jul 14 '21 at 07:19
  • @mjwills I clarify the problem to make sure there is no misunderstanding. My back-end server is sending request to another back-end server over SSL. When my back-end server gets idle, it can't communicate with that back-end server on first or second try. Then it communicates with that server without any problem. I don't think any of those servers don't responding. It is more likely there is a specific built in mechanism for sending network requests in .Net applications that should be somehow handled, which ignores my `ServicePointManager.ServerCertificateValidationCallback` on first tries. – Masoud Keshavarz Jul 14 '21 at 07:48

0 Answers0