Thursday, May 17, 2012

Как программно подключиться к SharePoint сайту с неправильным сертификатом. Обход ошибки: Could not establish trust relationship for the SSL/TLS secure channel.

Нашел решение здесь.
В кратце схема такая:
  1. В программе создаем новый метод
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;

    /// <summary>
    /// solution for exception
    /// System.Net.WebException:
    /// The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
    /// </summary>
    public static void BypassCertificateError()
    {
      ServicePointManager.ServerCertificateValidationCallback += delegate(Object sender1,X509Certificate certificate,X509Chain chain,SslPolicyErrors sslPolicyErrors)
    {
    return true;
    };
    }
  2. Перед подключением к сайту вызываем этот метод:
    private void buttonStart_Click(object sender, EventArgs e)
    {
    string siteURL = "https://cms.flyuia.com/it";
    using (ClientContext siteCont = new ClientContext(siteURL))
    {
    siteCont.Credentials = System.Net.CredentialCache.DefaultCredentials;
    //Здесь свой код
    BypassCertificateError();
    siteCont.ExecuteQuery();
    }
    }

No comments:

Post a Comment