HttpClient HTTPS Request With Certificate-C#

Recently in my project, I wanted to test SSL validation in my Unit Test while Making a HttpClient request. This article will show you how to read the certificate file in C# and add it to HttpClient.

How to convert certificates to Base64 (.cer) format

  1. Open Certificate
  2. Click on the Details Tab
  3. Click on Copy to File.
  4. Select Base-64 encoded X.509.

The code is straightforward. $ads={1}

       private X509Certificate2 GetClientTestingCertificate(string certificate)
            X509Certificate2 certificate2 = null;
                var privateKeyBytes = Convert.FromBase64String(certificate);
                var pfxPassword = "";
                certificate2 = new X509Certificate2(privateKeyBytes, pfxPassword, X509KeyStorageFlags.Exportable);

                return certificate2;
            catch (Exception)

            return certificate2;

How to use

var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.SslProtocols = SslProtocols.Tls12;
handler.ClientCertificates.Add(GetClientTestingCertificate("base64 data"));
var client = new HttpClient(handler);

Next Post Previous Post
No Comment
Add Comment
comment url