[C#]使用HttpWebRequest请求远端服务器时如何加载SSL证书

 

首先加上引用“System.Security.DLL”, 其次在工程中 using System.Security.Cryptography.X509Certificates;这样就可以使用"X509Certificate Class”了,它的定义参见http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemsecuritycryptographyx509certificatesx509certificateclasstopic.asp

之后我们就可以

/// 构建请求的HttpWebRequest对象

HttpWebRequest hwrRequest = (HttpWebRequest)WebRequest.Create( strValidatePageURL);

/// 从本地文件中加载证书

hwrRequest.ClientCertificates.Add(X509Certificate.CreateFromCertFile("c:\\motor.https.pem.cer"));

这是一个较简单的办法。

如果你遇到了“The underlying connection was closed. Could not establish a secure SSL/TLS connection"”的异常,那么请设置

hwrRequest.KeepAlive = true;

如果您使用的是CreateFromSignedFile来创建证书,那么请您务必注意,即使CreateFromSignedFile没有能够从文件中创建证书,甚至即使没有找到该文件,他也不会抛出异常,也不返回null,只是他的各个字段为null。

所以,。。。,还是请使用CreateFromCertFile好了。

至于如何在个人证书存储区获取证书,参看下面的blog

参看: WSE2.0中X509安全令牌的使用

和 调用web service如何加载证书 . 

posted @ 2012-03-01 16:13  Chaoa  阅读(1307)  评论(0编辑  收藏  举报