使用证书从.net调用php webservice

时间:2010-07-22 14:07:41

标签: c# php web-services certificate

我正在使用c#中的代码来调用受用户/密码和证书保护的php Web服务:

string wsurl = ConfigurationManager.AppSettings["Url"];
string wsuser = ConfigurationManager.AppSettings["User"];
string wspass = ConfigurationManager.AppSettings["Pass"];

string url = string.Format(wsurl, param1, param2);

System.Net.CredentialCache oCredentialCache = new System.Net.CredentialCache();
oCredentialCache.Add(new System.Uri(url), "Basic",
    new System.Net.NetworkCredential(wsuser, wspass));

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = TIMEOUT;
req.Credentials = oCredentialCache;
req.Method = "GET";

AttachCert(req);

//Get the data as an HttpWebResponse object
WebResponse resp = req.GetResponse();

从我的devel机器运行时,这可以正常工作,但是当我们将它上传到服务器时,我在调用GetResponse()时遇到Timeout错误。

AttachCert()调用是我将证书附加到请求的地方,如果我评论此行,我没有得到超时但是正确的错误,说由于缺少证书而无法完成调用。 这是AttachCert代码:

public static void AttachCert(HttpWebRequest Request)
{
    // Obtain the certificate. 
    string certpath = ConfigurationManager.AppSettings["CertPath"];

    X509Certificate Cert = X509Certificate.CreateFromCertFile(certpath);
    ServicePointManager.CertificatePolicy = new CertPolicy();

    Request.ClientCertificates.Add(Cert);
}

知道为什么这可以在我的机器上运行但不在服务器上运行?我们尝试删除Web服务上的证书,并且它按预期工作。所以在那次电话会议上显然有些奇怪,但我无法弄清楚是什么。

由于 Vicenç

1 个答案:

答案 0 :(得分:1)

尝试注册此回调并注意任何错误。

public static bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
  // check for errors
  // just return true to accept any certificate (self signed etc)
}

ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(MyClass.ValidateRemoteCertificate);

我希望它有所帮助。