views:

671

answers:

2

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. Basicly, 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
+1  A: 

Just subclass WebClient, add your own ClientCertificates property and override the WebClient.GetWebRequest(System.Uri) method. I don't have time to convert this to C# from VB but it should be fairly self-explanatory:

Imports System.Net

Public Class WebClient2
    Inherits System.Net.WebClient

    Private _ClientCertificates As New System.Security.Cryptography.X509Certificates.X509CertificateCollection
    Public ReadOnly Property ClientCertificates() As System.Security.Cryptography.X509Certificates.X509CertificateCollection
        Get
            Return Me._ClientCertificates
        End Get
    End Property
    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Dim R = MyBase.GetWebRequest(address)
        If TypeOf R Is HttpWebRequest Then
            Dim WR = DirectCast(R, HttpWebRequest)
            If Me._ClientCertificates IsNot Nothing AndAlso Me._ClientCertificates.Count > 0 Then
                WR.ClientCertificates.AddRange(Me._ClientCertificates)
            End If
        End If
        Return R
    End Function
End Class
Chris Haas
+2  A: 

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;
    }
}
Mikael Svenson
Thank You, this worked great.
Andrew