HttpClient with HttpClientHandler with x509 certificate doesn't work in .NET FW 4.8 but working in .NET 8.0

32 Views Asked by At

I have implemented HttpClient with a HttpClientHandler to attach a X509 certificate.

private HttpClientHandler PrepareClientHandler(string certpath, string certPassword)
{
    var handler = new HttpClientHandler();
    handler.ClientCertificateOptions = ClientCertificateOption.Manual;
    handler.SslProtocols = SslProtocols.Tls12;
    handler.ClientCertificates.Add(new X509Certificate2(certpath, certPassword));
    return handler;
}
HttpClientHandler handler = PrepareClientHandler(certpath, certPassword);

using (var client = new HttpClient(handler))
{
    client.Timeout = TimeSpan.FromMinutes(10);

    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CreateRsaToken(certpath, certPassword));
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var uri = webApiURL;
    var response = client.GetAsync(uri).Result;
    var responseMessage = response.Content.ReadAsStringAsync().Result;

    if (response.IsSuccessStatusCode)
    {
        return JsonConvert.DeserializeObject<Response>(responseMessage);
    }
    else
    {
        ///Error
    }
}

This code works in a .NET 8.0 console application, but it's not working in .NET Framework 4.8. It seems like the handler is not working in .NET 4.8. Can anyone help me with this?

0

There are 0 best solutions below