And*_*rew 71 c# webclient certificate http-post httpwebrequest
我知道将证书添加到HttpWebRequest非常简单.但是,我还没有找到使用WebClient进行等效的方法.基本上,我想使用WebClient发送带有特定证书的POST.
您将如何使用WebClient完成此确切代码:
var request = (HttpWebRequest) WebRequest.Create("my-url");
request.Method = "POST";
request.ClientCertificates.Add(new X509Certificate()); //add cert
Run Code Online (Sandbox Code Playgroud)
Mik*_*son 91
您必须子类化并覆盖一个或多个函数.
class MyWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
request.ClientCertificates.Add(new X509Certificate());
return request;
}
}
Run Code Online (Sandbox Code Playgroud)
yop*_*038 11
public class CertificateWebClient : WebClient
{
private readonly X509Certificate2 certificate;
public CertificateWebClient(X509Certificate2 cert)
{
certificate = cert;
}
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate X509certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
{
return true;
};
request.ClientCertificates.Add(certificate);
return request;
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以使用自签名证书!("底层连接已关闭:无法为SSL/TLS安全通道建立信任关系.;底层连接已关闭:无法为SSL/TLS安全通道建立信任关系.")
X509Certificate2 Cert = new X509Certificate2("client.p12", "1234", X509KeyStorageFlags.MachineKeySet);
// Create a new WebClient instance.
CertificateWebClient myWebClient = new CertificateWebClient(Cert);
string fileName = Installation.destXML;
string uriString = "https://xxxxxxx.xx:918";
// Upload the file to the URI.
// The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
byte[] responseArray = myWebClient.UploadFile(uriString, fileName);
// Decode and display the response.
Console.WriteLine("\nResponse Received.The contents of the file uploaded are:\n{0}",
System.Text.Encoding.ASCII.GetString(responseArray));
Run Code Online (Sandbox Code Playgroud)
小智 5
在我们的前端安装新证书时发生了一件有趣的事情。我们开始收到错误:
“底层连接已关闭:无法为 SSL/TLS 安全通道建立信任关系。;底层连接已关闭:无法为 SSL/TLS 安全通道建立信任关系。”
我们通过转到每个前端并打开浏览器来处理错误。似乎 IE 正在缓存旧证书。通过打开浏览器,新证书生效。问题解决了!
| 归档时间: |
|
| 查看次数: |
76070 次 |
| 最近记录: |