【问题标题】:Webclient DownloadFile with ClientCertificate带有 ClientCertificate 的 Webclient 下载文件
【发布时间】:2016-07-01 08:45:34
【问题描述】:
我正在尝试在 url 上下载 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);
}
【问题讨论】:
标签:
c#
certificate
webclient
【解决方案1】:
我终于得到了一个解决方案:覆盖 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);
}
【解决方案2】:
如果有人偶然发现这个问题和答案,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);
}