The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. at System.Net.HttpWebRequest.GetResponse()

Dimitris Vlachopoulos 1 Reputation point
2022-03-01T15:41:37.867+00:00

Hello guys,

I try to fix a bug but I can't find something that really helps me.

I do a HttpWebRequest but it gives me the error "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
at System.Net.HttpWebRequest.GetResponse()" when I go to get response .

I have already done to put "ServicePointManager.SecurityProtocol" equal to TLS 1.2

HttpWebRequest request;
ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;
ServicePointManager.DefaultConnectionLimit = 9999;
request = (HttpWebRequest)WebRequest.Create(uri);

But when I go to get the response:

HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();

It gives me the error that I mentioned above.

Also I try to bypass the Certificate with:

ServicePointManager.ServiceCertificateValidationCallback = new RemoteCertificateValidationCallback ( delegate { return true; } );

With the above code it works fine but I think with this piece of code I will have security issues.

Any ideas what can I do to fix this error?

I use .NET Framework 4.5.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,386 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 49,246 Reputation points
    2022-03-01T18:02:54.867+00:00

    Note, I assume you mean TLS 1.2, not 2.1.

    Yes you will have a security issue. You're trying to talk to a service that requires SSL for encrypted communications. Disabling it would prevent that assuming the remote host even allowed non-HTTPS communication.

    The problem is that your app isn't using a version of SSL that the remote server requires. Simply setting a value in the code doesn't automatically enable the feature. The server hosting your app must have TLS 1.2 enabled and the framework must be updated to allow for using that protocol. Since you are using .NET 4.5 then it doesn't support TLS 1.2 out of the box. To fix this you need to follow the steps here. Specifically you need to either upgrade the framework version on the machine to a newer version (4.7+) or apply the appropriate hotfixes and then set the necessary registry entries as discussed in the document.

    0 comments No comments