C#中实现https的双向认证
问题:
【SSL】WebClient 请求 https 页面出错:未能创建 SSL/TLS 安全通道
代码:
/** post 表单的方式发送请求数据 **/ public String sendMessage(String postUrl, NameValueCollection postData) { ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); //WebClient web = new WebClient(); //byte[] respData = web.UploadValues(postUrl, "POST", postData); //String resp = Encoding.UTF8.GetString(respData); String resp; using (SecureWebClient client = new SecureWebClient()) { byte[] respData = client.UploadValues(postUrl, "POST", postData); resp = Encoding.UTF8.GetString(respData); } return resp; } /// <summary> /// 总是接受 认证平台 服务器的证书 /// </summary> /// <param name="sender"></param> /// <param name="certificate"></param> /// <param name="chain"></param> /// <param name="errors"></param> /// <returns></returns> public static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors) { // 总是接受 认证平台 服务器的证书 return true; } /// <summary> /// https双向认证 /// </summary> public class SecureWebClient : WebClient { /// <summary> /// 加载证书 /// </summary> /// <param name="address"></param> /// <returns></returns> protected override WebRequest GetWebRequest(Uri address) { HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address); var cer = new X509Certificate2(Config.GetValue("MinSheng_custPriPfxPath"), Config.GetValue("MinSheng_custPriPfxPwd")); request.ClientCertificates.Add(cer); return request; } }
注:
当调用 X509Certificate2 的时候,会提示找不到文件而报错。
发现文件也是存在的,就是这个函数读取不了,网上查了一下,发现是IIS的程序池配置问题,云服务器上的自动加载配置文件设为Fasle的,只要在你网站的程序池中,设置为True就解决了。