简体   繁体   中英

How to write this line in C++/CLI?

I'm using Visual C++ to call a web service. I need to bypass the invalid SSL certificates since I'm getting this error -

The request failed. The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

While writing the same thing in C#, I used this line -

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

and it worked for me.

How do I achieve the same thing in Visual C++? How do I write the same line in Visual C++?

You need to create callback object explicitly and assign it to corresponding property.

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;
}

C++/CLI in VS 2010 doesn't support lambdas, so you'll have to write your delegate as a normal function:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM