简体   繁体   中英

SSL connection could not be established

I've got an issue with sending HTTP requests to as part of automation testing, I want to check URL's status code. When I send the request I have an Exception:

System.AggregateException: 'One or more errors occurred. (The SSL connection could not be established, see inner exception.)'

The inner exceptions are:

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

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

SocketException: An existing connection was forcibly closed by the remote host.

My code:

    public HttpStatusCode SendRequest(string _url)
    {
        SetUrl(_url);

        HttpClientHandler clientHandler = new HttpClientHandler();
        clientHandler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => { return true; };
        clientHandler.SslProtocols = SslProtocols.Tls;

        HttpClient client = new HttpClient(clientHandler);

        var response = client.GetAsync(Url).Result;

        StatusCode = response.StatusCode;

        return StatusCode;
    }

Thank you in advance !

The remote host does (rightfully) not accept that you want to connect using TLS 1.0, which is deprecated.

Specify .Tls12 or .Tls13.

As @CodeCaster already mentioned: SslProtocols.Tls (TLS 1.0) is not an option nowadays. Simply use SslProtocols.None (which is the default) to let the OS choose the best option for you:

None: Allows the operating system to choose the best protocol to use, and to block protocols that are not secure. Unless your app has a specific reason not to, you should use this field.

https://docs.microsoft.com/en-us/dotnet/api/system.security.authentication.sslprotocols?view=net-5.0#fields

Furthermore skipping the server certificate validation (by letting ServerCertificateCustomValidationCallback just return true) is a very dangerous thing. You should avoid that.

Is the remote host under your control? Can you check which TLS version it's using?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM