クイック スタート: Web API のサンプル (C#)

このクイック スタートでは、Microsoft Dataverse 環境に接続して、Web API WhoAmI 関数 を呼び出すための簡単なコンソール アプリケーションを作成します。 この関数は、ログオンした Dataverse ユーザーに関する情報を取得します。 ここで説明する基本的な機能を理解したら、Dataverse テーブルの行を作成、取得、更新、削除するなど、他の Web API 操作に進むことができます。

このプログラムは、HttpClient を認証して使用し、GET 要求を WhoAmI 関数 に送信します。 この応答は、WhoAmIResponse ComplexType です。 その後、プログラムは応答から取得した UserId プロパティ値を表示します。

注意

これは、最小限のコードで接続する方法を示す、非常に単純な例です。

この .NET 6 プロジェクトの完全な Visual Studio ソリューションは、dataverse/webapi/C#-NETx/QuickStart の下の PowerApps-Samples リポジトリで確認することができます。 また、dataverse/webapi/C#/QuickStart の下に、サンプルの .NET Framework バージョンもあります。

前提条件

  • Visual Studio 2022 またはそれ以降
  • インターネット接続
  • Dataverse 環境に有効なユーザー アカウント
  • 接続に使用したい Dataverse 環境への URL
  • C# 言語に関する基本的な理解

注意

認証するには、アプリを Microsoft Entra ID に登録する必要があります。 このクイック スタート サンプルは、Microsoft が公開している実行中のサンプル コードの目的で使用できるアプリ登録 clientid 値を示します。 ただし、独自のカスタム アプリケーションの場合は、それを AD に登録する必要があります。 詳細情報: チュートリアル: Microsoft Entra ID でアプリを登録する

Visual Studio プロジェクトの作成

  1. Visual Studio 2022 を起動して、新しいプロジェクトの作成 を選択します。

    新しいプロジェクトの作成

  2. 新しい コンソール アプリ プロジェクトを作成します。

    新しいコンソール アプリケーション プロジェクト

  3. 場所プロジェクト名 を設定して、プロジェクトを構成します。

    プロジェクトを構成する

  4. .NET 6.0 (長期サポート) および トップ レベル ステートメントを使用しない を選択して、プロジェクトを構成します。 その後、作成 をクリックします。

    追加情報ダイアログ。

  5. Solution Explorer で、作成したプロジェクトを右クリックして、コンテキスト メニューで NuGet パッケージの管理... を選択します。 NuGet では、必要なアセンブリをプロジェクトに取り込むことができます。

  6. Microsoft.Identity.Client という名のの Microsoft 認証ライブラリ (MSAL) NuGet パッケージを選び、インストールを選択します。

    (MSAL) 属性パッケージをインストール

    注意

    インストールする前に、ライセンス条項への同意を求めるメッセージが表示されます。 ライセンスの承認 ダイアログで 同意する をクリックします。

Program.cs を編集する

次の手順に従って、メイン プログラムのコードを追加します。

  1. Program.cs のコンテンツ全体を次のコードに置き換えます。

    using Microsoft.Identity.Client;  // Microsoft Authentication Library (MSAL)
    using System;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text.Json;
    using System.Threading.Tasks;
    
    namespace PowerApps.Samples
    {
       /// <summary>
       /// Demonstrates Azure authentication and execution of a Dataverse Web API function.
       /// </summary>
       class Program
       {
          static async Task Main()
          {
                // TODO Specify the Dataverse environment name to connect with.
                // See https://learn.microsoft.com/power-apps/developer/data-platform/webapi/compose-http-requests-handle-errors#web-api-url-and-versions
                string resource = "https://<env-name>.api.<region>.dynamics.com";
    
                // Microsoft Entra ID app registration shared by all Power App samples.
                var clientId = "51f81489-12ee-4a9e-aaae-a2591f45987d";
                var redirectUri = "http://localhost"; // Loopback for the interactive login.
    
                // For your custom apps, you will need to register them with Microsoft Entra ID yourself.
                // See https://docs.microsoft.com/powerapps/developer/data-platform/walkthrough-register-app-azure-active-directory
    
                #region Authentication
    
                var authBuilder = PublicClientApplicationBuilder.Create(clientId)
                               .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
                               .WithRedirectUri(redirectUri)
                               .Build();
                var scope = resource + "/user_impersonation";
                string[] scopes = { scope };
    
                AuthenticationResult token =
                   await authBuilder.AcquireTokenInteractive(scopes).ExecuteAsync();
                #endregion Authentication
    
                #region Client configuration
    
                var client = new HttpClient
                {
                   // See https://docs.microsoft.com/powerapps/developer/data-platform/webapi/compose-http-requests-handle-errors#web-api-url-and-versions
                   BaseAddress = new Uri(resource + "/api/data/v9.2/"),
                   Timeout = new TimeSpan(0, 2, 0)    // Standard two minute timeout on web service calls.
                };
    
                // Default headers for each Web API call.
                // See https://docs.microsoft.com/powerapps/developer/data-platform/webapi/compose-http-requests-handle-errors#http-headers
                HttpRequestHeaders headers = client.DefaultRequestHeaders;
                headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
                headers.Add("OData-MaxVersion", "4.0");
                headers.Add("OData-Version", "4.0");
                headers.Accept.Add(
                   new MediaTypeWithQualityHeaderValue("application/json"));
                #endregion Client configuration
    
                #region Web API call
    
                // Invoke the Web API 'WhoAmI' unbound function.
                // See https://docs.microsoft.com/powerapps/developer/data-platform/webapi/compose-http-requests-handle-errors
                // See https://docs.microsoft.com/powerapps/developer/data-platform/webapi/use-web-api-functions#unbound-functions
                var response = await client.GetAsync("WhoAmI");
    
                if (response.IsSuccessStatusCode)
                {
                   // Parse the JSON formatted service response (WhoAmIResponse) to obtain the user ID value.
                   // See https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/whoamiresponse
                   Guid userId = new();
    
                   string jsonContent = await response.Content.ReadAsStringAsync();
    
                   // Using System.Text.Json
                   using (JsonDocument doc = JsonDocument.Parse(jsonContent))
                   {
                      JsonElement root = doc.RootElement;
                      JsonElement userIdElement = root.GetProperty("UserId");
                      userId = userIdElement.GetGuid();
                   }
    
                   // Alternate code, but requires that the WhoAmIResponse class be defined (see below).
                   // WhoAmIResponse whoAmIresponse = JsonSerializer.Deserialize<WhoAmIResponse>(jsonContent);
                   // userId = whoAmIresponse.UserId;
    
                   Console.WriteLine($"Your user ID is {userId}");
                }
                else
                {
                   Console.WriteLine("Web API call failed");
                   Console.WriteLine("Reason: " + response.ReasonPhrase);
                }
                #endregion Web API call
          }
       }
    
       /// <summary>
       /// WhoAmIResponse class definition 
       /// </summary>
       /// <remarks>To be used for JSON deserialization.</remarks>
       /// <see cref="https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/whoamiresponse"/>
       public class WhoAmIResponse
       {
          public Guid BusinessUnitId { get; set; }
          public Guid UserId { get; set; }
          public Guid OrganizationId { get; set; }
       }
    }
    
  2. 上記のコードの TODO コメントのすぐ下で、resource 変数値を Dataverse テスト環境の実際の URL と置換します。 テスト環境の URL 値を見つけるには、次の手順に従います。

    1. ブラウザーで Power Apps に移動します。
    2. (検索フィールドの右側にある) 環境アイコンを選択し、テスト環境を選択します。
    3. 設定アイコン設定ボタンを選択し、 開発者のツールとリソースを選択します。
    4. Web API エンドポイントの URL を、末尾の /api/data/v9.2 を除いた "https:" から ".com" までコピーします。
    5. プログラム コードのリソース文字列値を、そのエンドポイント URL 値に置き換えます。 例:

      string resource = "https://contoso.api.crm.dynamics.com";

プログラムを実行する

  1. F5 キーを押して、プログラムをビルドして実行します。

    ブラウザー ウィンドウが開き、アカウントを選択するよう求められます。 Dataverse 環境へのアクセスに使用するアカウントを選択します。 そのアカウントがリストに表示されない場合は、別のアカウントを使用する をクリックします。

    アカウントを選択したら、パスワードを入力して サインイン をクリックします。

  2. コンソール アプリケーション ウィンドウを参照します。 出力は次のようになります。

    Your user ID is 4026be43-6b69-e111-8f65-78e7d1620f5e
    
    C:\Projects\webapi-quickstart\bin\Debug\net6.0\webapi-quickstart.exe (process 21524) exited with code 0.
    To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
    Press any key to close this window . . .
    

おつかれさまでした!

Web API に正常に接続されました。

クイック スタートのサンプルでは、Visual Studio プロジェクトを作成する簡単な方法を示しており、例外処理やアクセス トークンを更新するメソッドは使用していません。 接続できることを確認し、さまざまな操作を試すにはこれで十分です。

推奨される設計パターンを示す詳しい例については、 WebAPIService クラス ライブラリ (C#) を参照してください。 これは、Web APIデータ操作サンプル (C#) に使用するプロジェクトです。 実際の動作:

  • .NET の回復性と一時的なエラー処理ライブラリ Polly による Dataverse サービス保護 API 制限の管理。
  • IHttpClientFactory を使用した .NET での HttpClient の管理。
  • 構成データを使用したクライアントの動作の管理。
  • Dataverse Web API によって返されるエラーの管理。
  • コード再利用のパターン:
    • HttpRequestMessageHttpResponseMessage を継承するクラスの作成。
    • これらのクラスを使用するメソッド。
    • 必要に応じて新しい機能を追加するためのモジュール パターン。

次の手順

Web アプリケーションの作成を試みます。

サービス ドキュメントを理解することで、Dataverse Web API 機能の詳細を学びます。

注意

ドキュメントの言語設定についてお聞かせください。 簡単な調査を行います。 (この調査は英語です)

この調査には約 7 分かかります。 個人データは収集されません (プライバシー ステートメント)。