如何在c++ /CLI中编写这一行

本文关键字:一行 c++ CLI | 更新日期: 2023-09-27 18:18:39

我正在使用Visual c++调用web服务。我需要绕过无效的SSL证书,因为我得到这个错误-

请求失败。底层连接已关闭:无法为SSL/TLS安全通道建立信任关系。

在c#中写同样的东西时,我使用了这一行-

System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

,它对我有效。

如何在Visual c++中实现同样的事情?如何在Visual c++中编写同一行?

如何在c++ /CLI中编写这一行

您需要显式地创建回调对象并将其分配给相应的属性。

using namespace System;
using namespace System::Net;
using namespace System::Net::Security;
using namespace System::Security::Cryptography::X509Certificates;

static bool ValidateServerCertificate(
        Object^ sender,
        X509Certificate^ certificate,
        X509Chain^ chain,
        SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }
int main(array<System::String ^> ^args)
{
    // create callback object, pointing to your function
    System::Net::Security::RemoteCertificateValidationCallback^ clb = gcnew RemoteCertificateValidationCallback(ValidateServerCertificate);
    // assign it to the property
    System::Net::ServicePointManager::ServerCertificateValidationCallback = clb;
    return 0;
}

VS 2010中的c++/CLI不支持lambdas,因此您必须将委托编写为普通函数:

using namespace System::Net;
using namespace System::Net::Security;
using namespace System::Security::Cryptography::X509Certificates;
bool returnTrueCallback(
    Object^ sender, X509Certificate^ certificate, X509Chain^ chain,
    SslPolicyErrors sslPolicyErrors)
{
    return true;
}
...
ServicePointManager::ServerCertificateValidationCallback =
    gcnew RemoteCertificateValidationCallback(returnTrueCallback);