调用web service如何加载证书

在调用web service时,如果web service需要客户端证书,也就是需要走ssl协议,那么在调用的时候就需要加载上一个客户端证书,这个客户端证书是一个.cer文件,可以从浏览器的证书中导出,在导出的时候不用导出私钥,这样导出的证书是不包含私钥的,也即这个证书文件拷贝到其它机器是无效的。
在调用的时候比较简单。如下:
        // The path to the certificate.
        string Certificate =  "Certificate.cer";

        // Load the certificate into an X509Certificate object.
        X509Certificate cert = X509Certificate.CreateFromCertFile(Certificate);
        
        LoginService srv = new LoginService();
        srv.ClientCertificates.Add(cert);

如果不加载这个证书就会返回403禁止访问错误。
另外为了避免每次new的时候都采用代码加载证书,可以直接修改ws的代理类,比如:
    public LoginService() {
            string urlSetting = System.Configuration.ConfigurationSettings.AppSettings["LoginPlugin.localhost.LoginService"];
            if ((urlSetting != null)) {
                this.Url = string.Concat(urlSetting, "");
            }
            else {
                this.Url = "http://localhost/Jiancha2/Services/LoginService.asmx";
            }
   if (System.Configuration.ConfigurationSettings.AppSettings["ssl"] == "true" && Ocean.Plugins.CertInfo.Cert != null)
   {
            this.ClientCertificates.Add(Ocean.Plugins.CertInfo.Cert);
   }
    }

至于证书服务器和web服务器如何支持ssl,这个在dev-club的电子杂志上有一期有专门的讲解,我就不多说了。

posted on 2004-10-12 13:45  ocean  阅读(6515)  评论(3编辑  收藏  举报

导航