Search code examples
c#.nethttpsssl-certificaterestsharp

How can I upload .crt and .key file when making a Restsharp request?


I have specified a host by uploading my .crt and .key files to the certificates section of the settings tab for Postman, and I have no problem making requests through postman. However, when requesting with restsharp, I am getting an error even though I add the certificate as follows. I was able to add .crt and .key files in Postman, but only .crt in code. The error message I got was "The SSL connection could not be established, see inner exception." shaped. How can I add .crt and .key files to restsharp when making requests from within the code? If .crt is sufficient why am I getting this error?

var options = new RestClientOptions("https://uri");
options.ClientCertificates = new X509CertificateCollection();
options.ClientCertificates.Add(new X509Certificate2(@"C:\name.crt"));
RestClient restClient = new RestClient(options);
RestRequest restRequest = new RestRequest("/token", requestModel.Method);
RestResponse restResponse = restClient.Execute(restRequest); 

Solution

  • The key can be included by combining the .crt & .key files into one Personal Information Exchange (.pfx) file.

    Then instead of passing the .crt file, pass the .pfx file...

    options.ClientCertificates.Add(
        new X509Certificate2(@"C:\name.pfx", "password_for_pfx"));