Search code examples
c#httpwebrequestcertificatewebclienthttp-post

How can you add a Certificate to WebClient (C#)?


I know it is pretty simple to add a certificate to a HttpWebRequest. However, I have not found a way to do the equivalent using WebClient. Basically, I want to send out a POST with a specific certificate using WebClient.

How would you accomplish this exact code using WebClient:

var request = (HttpWebRequest) WebRequest.Create("my-url");
request.Method = "POST";
request.ClientCertificates.Add(new X509Certificate()); //add cert

Solution

  • You must subclass and override one or more functions.

    class MyWebClient : WebClient
    {
        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
            request.ClientCertificates.Add(new X509Certificate());
            return request;
        }
    }