使用ClientCertificate的Webclient DownloadFile

时间:2016-07-01 08:45:34

标签: c# certificate webclient

我正在尝试在网址上下载pfx文件。在我打开链接的Chrome上,我必须选择一个证书,然后登录。但是当我用C#WebClient尝试它时,我得到了一个错误403“Forbidden”。

如何以编程方式指定证书或绕过此步骤?

我的代码:

using (var client = new System.Net.WebClient())
{
    client.Credentials = new System.Net.NetworkCredential(MyLogin, MyPassword);
    client.DownloadFile(MyUrl, MyFile);
}

2 个答案:

答案 0 :(得分:0)

我终于得到了一个解决方案:覆盖WebClient!

新的webClient:

public class MyWebClient : WebClient
{
    X509Certificate2 certificate;

    public MyWebClient(X509Certificate2 certificate)
        : base()
    {
        this.certificate = certificate;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
        request.ClientCertificates.Add(certificate);
        request.Credentials = this.Credentials;
        return request;
    }
}

使用它的方式:

using (var client = new MyWebClient(MyCertificate))
{
    // optional login/password if website require both. If not, don't set the credentials
    client.Credentials = new System.Net.NetworkCredential(MyLogin, MyPassword);
    client.DownloadFile(MyUrl, MyFile);
}

答案 1 :(得分:0)

如果有人偶然发现这个问题并回答,WebClient覆盖的实现应该有点不同。

public class ExtendedWebClient : System.Net.WebClient
{
    X509Certificate2 _certificate;

    public ExtendedWebClient() : base() { }

    public ExtendedWebClient(X509Certificate2 certificate) : base()
    {
        _certificate = certificate;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        // Base method creates HttpWebRequest and sets other needed stuff like POST method or authentication/authorization headers.
        HttpWebRequest request = (HttpWebRequest)base.Create(address);
        if(_certificate!=null && address.Schema=="https")
            request.ClientCertificates.Add(_certificate);            
        return request;
    }
}

然后在使用原件时使用它,或者在请求“htttps”时使用客户端证书

// For download
using(var client = new ExtendedWebClient(MyCertificate))
{
    // Add anything optional like authnetication or header here.
    client.DownloadFile(MyUrl, MyFile);
}

// ...

// Or for upload
using(var client = new ExtendedWebClient(MyCertificate))
{
    // Add anything optional like authnetication or header here.
    client.UploadFile(MyUrl, "POST", MyFile);
}