4

Hey all – been having some troubles figuring out how to pass a certificate when calling a REST web service in C#. I’ve been looking at various code snippets but can’t seem to figure out what I need to do. Below is some code I have with my application that calls a REST service without a certificate which works great. I’m assuming there’s some commands to add the cert to the code I have to allow that to work but that’s where I’m getting stuck. Not sure if I should be calling the service differently if a certificate is needed. I would imagine I need to look at the certificate store and search for it by thumbprint and add it to the HttpClient.

Also I am on .Net 4.5.

 string URL = "https://RESTSvcURL/function"; HttpClient client = new HttpClient(); client.BaseAddress = new Uri(URL); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync(urlParameters).Result; if (response.IsSuccessStatusCode) tbOutput.Text = response.Content.ReadAsStringAsync().Result; else tbOutput.Text = "Error: " + response.StatusCode + " " + response.ReasonPhrase; 

Also I will say that I do have a valid certificate created and installed. I can call the REST call manually by pulling the URL up in a browser and providing the cert and it does return data as expected.

1 Answer 1

3

The client certificates get specified on HttpClientHandler. HttpClient's default ctor will make a handler for you. In this case you need to specify it.

HttpClientHandler handler = new HttpClientHandler(); handler.ClientCertificates.Add(clientCert); HttpClient client = new HttpClient(handler); // continue with the rest of your code 
Sign up to request clarification or add additional context in comments.

2 Comments

Hmm - using the 'ClientCertificates' doesn't seem to be available in my environment. Looking it seems that's new as of 4.7.1 framework so I'll need to see if that's available on the environments this would be running on. If not I'll need to find another approach.
Ok, I was able to update to 4.7.1 and this indeed did work. I did have to add this before to define the clientCert. HttpClientHandler handler = new HttpClientHandler(); var certFile = Path.Combine(@"c:\certlocation\", "cert.pfx"); handler.ClientCertificates.Add(new X509Certificate2(certFile, "password"));

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.