我正在再次工作一个Web服务,其证书不是100%正确设置证书是为域* .domain1.com设置的,而api位于soap.shop.domain1.com/SOAP现在我不能连接到这个webservice,然后得到一个WebException“无法建立SSL / TLS安全通道的trush关系。 - > 根据验证程序,远程证书无效。
现在我的问题是有没有办法绕过这个检查我使用普通的Web引用(2.0)而不是服务引用..
答案 0 :(得分:8)
对于那些无法确定从哪里开始这个答案的人来说,这可能并不明显。上面的海报是正确的,但是对于如何处理给定代码并不是很明显。
假设您有一个类需要使用证书调用Web服务。
这是我完成的解决方案:
public class MyClass
{
public bool TrustAllCertificatesCallback(object sender, X509Certificate cert,
X509Chain chain, SslPolicyErrors errors)
{
return true;
}
public string CallSomeWebService(string someParam)
{
try
{
ServicePointManager.ServerCertificateValidationCallback = TrustAllCertificatesCallback;
RemoteWebService ws = new RemoteWebService();
//add the client cert to the web service call.
ws.ClientCertificates.Add(GetMyCert());
//call the web service
string response = ws.SomeMethod(someParam);
return response.ToString();
}
catch (Exception ex)
{throw;}
}
public X509Certificate GetMyCert()
{
try
{
string certPath = @"C:\MyCerts\MyCert.cer";
var cert = X509Certificate.CreateFromCertFile(certPath);
return cert;
}
catch (Exception ex)
{throw;}
}
}
答案 1 :(得分:6)
是的,您可以使用以下命令让ASP.NET忽略证书警告:
using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;
namespace YourNamespace
public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
{
public TrustAllCertificatePolicy() {}
public bool CheckValidationResult(ServicePoint sp, X509Certificate cert,WebRequest req, int problem)
{
return true;
}
}
}
答案 2 :(得分:5)
System.Net.ServicePointManager.ServerCertificateValidationCallback = _
Function(a, b, c, d) True
答案 3 :(得分:5)
选择你的味道..
lambda表达式
//Trust all certificates
System.Net.ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);
// trust sender (more secure)
System.Net.ServicePointManager.ServerCertificateValidationCallback
= ((sender, cert, chain, errors) => cert.Subject.Contains("YourServerName"));
或普通的clode(更适合测试)
// validate cert
// allows for validation of SSL conversations
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
// callback used to validate the certificate in an SSL conversation
private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
{
bool result = false;
if (cert.Subject.ToUpper().Contains("YourServerName"))
{
result = true;
}
return result;
}
答案 4 :(得分:3)
您需要处理验证证书的事件,并将其设置为始终返回true。有关详细信息,请参阅以下帖子:
http://8r13n.wordpress.com/2007/07/24/bypassing-certificate-validation-in-net/