我有一个简单的web服务调用,由。net (c#) 2.0 Windows应用程序生成,通过Visual Studio生成的web服务代理,用于同样用c#(2.0)编写的web服务。这种方法已经有效了好几年,并且在十几个正在运行的地方继续有效。

在新地点的新安装遇到了问题。当试图调用web服务时,它失败了,消息说:

无法为SSL/TLS安全建立信任关系 通道

web服务的URL使用SSL (https://)——但这已经在许多其他位置工作了很长时间(并继续这样做)。

我该往哪里看?这可能是Windows和。net之间的安全问题,是此安装独有的吗?如果是,我在哪里建立信任关系?我迷路了!


当前回答

如果没有工作坏证书,当ServerCertificateValidationCallback返回true; 我的ServerCertificateValidationCallback代码:

ServicePointManager.ServerCertificateValidationCallback += delegate
{
    LogWriter.LogInfo("Проверка сертификата отключена, на уровне ServerCertificateValidationCallback");
    return true;
};

我的代码被阻止执行ServerCertificateValidationCallback:

     if (!(ServicePointManager.CertificatePolicy is CertificateValidation))
    {
        CertificateValidation certValidate = new CertificateValidation();
        certValidate.ValidatingError += new CertificateValidation.ValidateCertificateEventHandler(this.OnValidateCertificateError);
        ServicePointManager.CertificatePolicy = certValidate;
    }

OnValidateCertificateError功能:

private void OnValidateCertificateError(object sender, CertificateValidationEventArgs e)
{
    string msg = string.Format(Strings.OnValidateCertificateError, e.Request.RequestUri, e.Certificate.GetName(), e.Problem, new Win32Exception(e.Problem).Message);
    LogWriter.LogError(msg);
    //Message.ShowError(msg);
}

我禁用了CertificateValidation代码和ServerCertificateValidationCallback运行得很好

其他回答

试试这个:

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

请注意,您必须至少使用4.5 .NET框架

想法(基于过去的痛苦):

do you have DNS and line-of-sight to the server? are you using the correct name from the certificate? is the certificate still valid? is a badly configured load balancer messing things up? does the new server machine have the clock set correctly (i.e. so that the UTC time is correct [ignore local time, it is largely irrelevent]) - this certainly matters for WCF, so may impact regular SOAP? is there a certificate trust chain issue? if you browse from the server to the soap service, can you get SSL? related to the above - has the certificate been installed to the correct location? (you may need a copy in Trusted Root Certification Authorities) is the server's machine-level proxy set correctly? (which different to the user's proxy); see proxycfg for XP / 2003 (not sure about Vista etc)

下面的代码片段将修复您正在调用的服务器上的SSL证书有问题的情况。例如,证书可能是自签名的,或者证书和服务器之间的主机名可能不匹配。

如果您正在调用您直接控制之外的服务器,这是危险的,因为您不能再确定您正在与您认为连接到的服务器通信。但是,如果您处理的是内部服务器,而获得“正确的”证书是不现实的,请使用以下命令告诉web服务忽略证书问题并勇敢地继续工作。

前两个使用lambda表达式,第三个使用常规代码。第一个接受任何证书。后两者至少检查证书中的主机名是否是您所期望的主机名。 ... 希望对你有帮助

//Trust all certificates
System.Net.ServicePointManager.ServerCertificateValidationCallback =
    ((sender, certificate, chain, sslPolicyErrors) => true);

// trust sender
System.Net.ServicePointManager.ServerCertificateValidationCallback
                = ((sender, cert, chain, errors) => cert.Subject.Contains("YourServerName"));

// validate cert by calling a function
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 = cert.Subject.Contains("YourServerName");
    return result;
}

我已经用了一段时间了如果有用的话。

调用方必须显式地请求需要不受信任的认证,并在完成时将回调放回默认状态。

    /// <summary>
    /// Helper method for returning the content of an external webpage
    /// </summary>
    /// <param name="url">URL to get</param>
    /// <param name="allowUntrustedCertificates">Flags whether to trust untrusted or self-signed certificates</param>
    /// <returns>HTML of the webpage</returns>
    public static string HttpGet(string url, bool allowUntrustedCertificates = false) {
        var oldCallback = ServicePointManager.ServerCertificateValidationCallback;
        string webPage = "";
        try {
            WebRequest req = WebRequest.Create(url);

            if (allowUntrustedCertificates) {
                // so we can query self-signed certificates
                ServicePointManager.ServerCertificateValidationCallback = 
                    ((sender, certification, chain, sslPolicyErrors) => true);
            }

            WebResponse resp = req.GetResponse();
        
            using (StreamReader sr = new StreamReader(resp.GetResponseStream())) {
                webPage = sr.ReadToEnd().Trim();
                sr.Close();
            }
            return webPage;
        }
        catch {
            // if the remote site fails to response (or we have no connection)
            return null;
        }
        finally {
            ServicePointManager.ServerCertificateValidationCallback = oldCallback;
        }
    }

我的解(VB。Net,这个应用程序的“登台”(UAT)版本需要与“登台”证书一起工作,但不影响请求一旦他们在现场):

    ...
        Dim url As String = ConfigurationManager.AppSettings("APIURL") & "token"
        If url.ToLower().Contains("staging") Then
           System.Net.ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
        End If
    ...

    Private  Function AcceptAllCertifications(ByVal sender As Object, ByVal certification As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
        Return True
    End Function