外部 Web サービスにアクセスする
プラグインとカスタム ワークフロー活動は、HTTP および HTTPS プロトコルを介してネットワークにアクセスできます。 この機能によって、ソーシャル サイト、ニュース フィード、Web サービスなどの一般的な Web サービスにアクセスできます。 このサンドボックスの機能には、次の Web アクセス制限が適用されます。
- サーバーには、現在の TLS スイートと暗号スイート が必要です。
- 許可されるプロトコルは HTTP および HTTPS だけです。
- localhost (loopback) へのアクセスは許可されません。
- IP アドレスは使用できません。 DNS による名前解決を必要とする名前付き Web アドレスを使用する必要があります。
- 匿名認証がサポートされ、その使用が推奨されます。 ログオン ユーザーの資格情報を入力または保存する必要はありません。
- サーバーは AzureCloud サービスタグで指定されている Power Platform および Dynamics 365 サービスの IP アドレス値からの接続を許可する必要があります。
Web サービスにアクセスする他の方法としては、Webhook および Azure Service Bus の使用などがあります。 それらのトピックの詳細については、次のセクションに記載されているリンクを参照してください。
外部 Web サービスにアクセスする方法
近年は、System.Net.Http.HttpClient Class に精通するユーザーが増えてきています。
HttpClient
は .NET Framework 4.5 で導入され、現在も利用可能な System.Net.WebClient Class を超える重要な機能を提供ししていますが、現在は廃止されています。
HttpClient
は再利用されることを意図しており、既定では非同期です。
HttpClient
は既定で非同期のため、通常の使用パターンから外れてコードを追加し、強制的に操作を同期的に実行する必要があります。通常は await
キーワードを削除し、非同期呼び出しに .GetAwaiter().GetResult()
を付加します。
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
{
// 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 (HttpClient client = new HttpClient())
{
client.Timeout = TimeSpan.FromMilliseconds(15000); //15 seconds
client.DefaultRequestHeaders.ConnectionClose = true; //Set KeepAlive to false
HttpResponseMessage response = client.GetAsync(webAddress).Result; //Make sure it is synchonrous
response.EnsureSuccessStatusCode();
string responseText = response.Content.ReadAsStringAsync().Result; //Make sure it is synchonrous
tracingService.Trace(responseText);
//Log success in the Plugin Trace Log:
tracingService.Trace("HttpClientPlugin completed successfully.");
}
}
catch (AggregateException aex)
{
tracingService.Trace("Inner Exceptions:");
foreach (Exception ex in aex.InnerExceptions) {
tracingService.Trace(" Exception: {0}", ex.ToString());
}
throw new InvalidPluginExecutionException(string.Format(CultureInfo.InvariantCulture,
"An exception occurred while attempting to issue the request.", aex));
}
}
catch (Exception e)
{
tracingService.Trace("Exception: {0}", e.ToString());
throw;
}
}
詳細情報: サンプル: プラグインからの Web アクセス
ベスト プラクティス
以下のベスト プラクティスの記事で説明します:
外部呼び出しに適切な Timeout
期間を設定して KeepAlive
を無効にする必要があります。 詳細については、前述のリンクを参照してください。