Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# calling REST service call and providing a certificate

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.

like image 202
Seril Avatar asked Oct 17 '25 22:10

Seril


1 Answers

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
like image 57
bartonjs Avatar answered Oct 20 '25 11:10

bartonjs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!