1

我需要将数据发送到需要证书授权的 webapi。这是使用WebRequestHandler在 .net 4.5.2 上运行的,但是当我尝试升级到 dotnet 5 并使用HttpClientHandler时 出现错误:

Message: The SSL connection could not be established, see inner exception., InnerException Message: Authentication failed because the remote party sent a TLS alert: 'HandshakeFailure'.

.net 4.5.2 代码

static async Task Main(string[] args)
    {
        try
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            var httpContent = new StringContent("json", System.Text.Encoding.UTF8, "application/json");

            var certificatepfx = new X509Certificate2(@"dpcert.pfx", "password");

            var handler = new WebRequestHandler();                
            handler.ClientCertificates.Add(certificatepfx);

            var httpClient = new HttpClient(handler);
            var response = await httpClient.PostAsync("someurl", httpContent);

            var returnValue = await response.Content.ReadAsStringAsync();
            Console.WriteLine(returnValue);

            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"error: {ex.Message} {ex.InnerException?.Message}");
        }
    }

.net 5 代码:

static async Task Main(string[] args)
    {
        try
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                return true;
            };

            var httpContent = new StringContent("json", System.Text.Encoding.UTF8, "application/json");

            var certificatepfx = new X509Certificate2(@"dpcert.pfx", "password");

            var handler = new HttpClientHandler
            {
                SslProtocols = SslProtocols.Tls13 | SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls,
                ClientCertificateOptions = ClientCertificateOption.Manual
            };

            handler.ClientCertificates.Add(certificatepfx);

            using var httpClient = new HttpClient(handler);
            var response = await httpClient.PostAsync("someurl", httpContent);

            var returnValue = await response.Content.ReadAsStringAsync();
            Console.WriteLine(returnValue);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"error: {ex.Message} {ex.InnerException?.Message}");
        }
    }

我的代码可能有什么问题?

4

0 回答 0