Posts Tagged ‘Public key certificate’

I was developing an application to post xml data to a URL (REST call) using and C#. The endpoint was hosted with a third party vendor and they had a much secured hosting environment. Their endpoints were https and they installed and generated the private client certificate (a password protected .p12 file) on their servers to prevent unwanted requests / hits.

So to access their endpoints one has to have that client certificate, basically any request to the endpoints should have the client certificate enclosed with the request data, even if you are requesting it from browser window you have to have that certificate installed in your browser.

To resolve the same first I installed that certificate on my development server, then I could able to request that URL from browser window. But when I did the same using my C# code using httpwebrequest object I got 403 forbidden error as the request was not sending the client certificate with xml data.

Ideally, if you have any .cer file you can add it with request object by using X509Certificate class but in case of private client certificate it just doesn’t work for that you have to use X509Certificate2 class, Here is the code snippet. You need to place the .p12 file in your webserver’s hard drive.

public string PostData(string DataToPost,string URL)
String result = “”;
String strPost = “RequestXML=” + DataToPost;
StreamWriter myWriter = null;

HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(URL);
objRequest.Method = “POST“;
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = “application/x-www-form-urlencoded”;

objRequest.ClientCertificates.Add(new X509Certificate2(@“E:\Certificate\clientcertificate.p12”, “password”));

myWriter = new StreamWriter(objRequest.GetRequestStream());
catch (Exception e)

HttpWebResponse objResponse = HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
result = sr.ReadToEnd();

// Close and clean up the StreamReader

return result;