Доступ к внешнему Rest API плагина MS Dynamics 365 Online выдает ошибку

#plugins #dynamics-crm #dynamics-crm-online #dynamics-crm-365

#Плагины #dynamics-crm #dynamics-crm-online #dynamics-crm-365

Вопрос:

Я пытаюсь получить доступ к внешнему стороннему API из плагина Dynamics 365 Online, используя следующий код:

 public void Execute(IServiceProvider serviceProvider)
    {
        //Extract the tracing service for use in plug-in debugging.
        ITracingService tracingService = 
            (ITracingService)serviceProvider.GetService(typeof(ITracingService));

        try
        {
            tracingService.Trace("Downloading the target URI: "   webAddress);

            try
            {
                //<snippetWebClientPlugin2>
                // Download the target URI using a Web client. Any .NET class that uses the
                // HTTP or HTTPS protocols and a DNS lookup should work.
                using (WebClient client = new WebClient())
                {
                    byte[] responseBytes = client.DownloadData(webAddress);
                    string response = Encoding.UTF8.GetString(responseBytes);
                    //</snippetWebClientPlugin2>
                    tracingService.Trace(response);

                    // For demonstration purposes, throw an exception so that the response
                    // is shown in the trace dialog of the Microsoft Dynamics CRM user interface.
                    throw new InvalidPluginExecutionException("WebClientPlugin completed successfully.");
                }
            }

            catch (WebException exception)
            {
                string str = string.Empty;
                if (exception.Response != null)
                {
                    using (StreamReader reader = 
                        new StreamReader(exception.Response.GetResponseStream()))
                    {
                        str = reader.ReadToEnd();
                    }
                    exception.Response.Close();
                }
                if (exception.Status == WebExceptionStatus.Timeout)
                {
                    throw new InvalidPluginExecutionException(
                        "The timeout elapsed while attempting to issue the request.", exception);
                }
                throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                    "A Web exception occurred while attempting to issue the request. {0}: {1}", 
                    exception.Message, str), exception);
            }
        }
        catch (Exception e)
        {
            tracingService.Trace("Exception: {0}", e.ToString());
            throw;
        }
    }
}
  

Но я получаю ошибку:

 Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.'
  

Я проверил документацию MS, но ничто не подсказывает, почему я не могу этого сделать. Я знаю о изолированных плагинах, но, согласно MS, я должен быть в состоянии сделать это, используя их собственный пример кода.

Комментарии:

1. Был ли мой ответ полезным?

Ответ №1:

Это ожидается в CRM Online, поскольку это SaaS, и вы находитесь в общем клиенте в облаке. Вы можете использовать webhook или Azure service hub, чтобы вызвать внешнюю конечную точку с контекстом CRM для обработки. Подробнее

И если у вас подключена CRM Online, то нормальным решением будет перенести обработку в среду, над которой у вас больше контроля. Наиболее распространенным вариантом является передача обработки в Azure с использованием служебной шины Azure или центра событий Azure. Альтернативный вариант, новый для CRM 9, заключается в отправке данных на WebHook, который может быть размещен где угодно.