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

 

対象: Dynamics 365 (online)、Dynamics 365 (on-premises)

このサンプルでは、Microsoft Dynamics 365 Server の認証方法、および基本的な Web API 操作、WhoAmI Function を呼び出す方法を示しています。 他の Web API サンプルとは異なり、このサンプルは他の非標準ヘルパー ライブラリまたは追加ソース ファイルには依存しません。 すべてのソース・コードは、1 個のファイル、Program.cs の中に入っており、ロジック フローおよび認証プロセスを簡単に理解する上で役に立ちます。 サンプルではオンライン、設置型およびインターネットに接続する展開 (IFDs) を使用します。

要件

このサンプルには以下の要件があります:

  • ソリューションを開き、構築するには、Microsoft Visual Studio 2015 以降が必要です。 この製品の無料のバージョンをダウンロードして入手できます: Visual Studio Express または Visual Studio Community

  • オンラインまたは設置型 Microsoft Dynamics 365 Server に接続するインターネットまたはネットワーク。

  • Microsoft Dynamics 365 Server (オンラインまたは設置型) のユーザー アカウント。

  • Dynamics 365 (オンライン) が使用されている場合、サンプル アプリケーションは、「チュートリアル: Azure Active Directory に Dynamics 365 アプリを登録する」で説明されているように Azure Active Directory に登録されている必要があります。

  • インターネットに接続する展開 (IFD) と共に Dynamics 365 (設置型) が使用されている場合、サンプル アプリケーションは、「チュートリアル: Active Directory に Dynamics 365 アプリを登録する」で説明されているように Active Directory テナントに登録されている必要があります。

重要

設計上、最初にソリューションは正常に作成されません。 ソース コードは //TODO コメントで示された行で編集し、ユーザー アカウントまたはアプリケーションの登録情報を入力します。

説明

この単純なサンプルは Web API を使用した開発に必要な 2 つの基本概念を示します: Microsoft Dynamics 365 Server に対する認証および HTTP プロトコルを使用した基本的な Web API 呼び出しの操作です。

クライアント アプリケーションがすべての Dynamics 365 リソースにアクセスできる前に認証が必要です。 このプロセスは、2 つの理由により重要である場合があります: 別の認証メカニズムはさまざまな展開の種類に必要とされ、Web ベース認証メカニズムは複数のプログラム手順を通常実行します。 設置型の展開に必要な Windows 統合認証は比較的単純であり、ユーザー名とパスワードのみを必要とします。 その後、プログラムは認証されたユーザーのエージェントとして後に機能します。

これに対して、オンラインと IFD 展開はクライアント アプリケーションの登録を事前と必要し、その後にマルチステップ OAuth 認証プロセスを使用します。Dynamics 365 (オンライン) の登録プロセスが、「チュートリアル: Azure Active Directory に Dynamics 365 アプリを登録する」の記事で説明されています。インターネットに接続する展開 (IFD) を使用する Dynamics 365 (設置型) の登録プロセスが、「チュートリアル: Active Directory に Dynamics 365 アプリを登録する」の記事で説明されています。 後続の各 Web API 要求は OAuth で認証する必要があります。 OAuth 認証の複雑さは、多くの場合、NuGet パッケージ Microsoft.IdentityModel.Clients.ActiveDirectory としてサンプルに追加される .NET クライアントに対して Active Directory 認証ライブラリ (ADAL) を使用することによって簡素化できます。 OAuth 認証は、メッセージ要求に必要とされる OAuth 承認ヘッダーを追加する OAuthMessageHandler クラスが組み込まれ、このサンプルでカプセル化されます。 将来のサンプルでは、認証機能のサポートは Web API ヘルパー ライブラリ に分割されます。 詳細については、「Microsoft Dynamics 365 でユーザーを認証する」を参照してください。

Dynamics 365 Web API は、OData 仕様 をベースとした REST API であるため、エンティティに対する標準化された HTTP 要求と関数とアクションの呼び出しをサポートします。 このサンプルでは、GET 要求を含む WhoAmI Function 関数の呼び出し、および HTTP 応答のこの関数によって提供されている情報の使用について示します。 複数の標準ライブラリは、この呼び出しのアシスタントとしてこのサンプルによって利用されます:

このサンプルの実行

まず、単純な Web API クイックスタート サンプル (C#) にアクセスして、サンプル アーカイブ ファイル Simple Web API quick-start sample (CS.zip) をダウンロードし、内容をローカル フォルダーに抽出します。 このフォルダには、次のファイルが含まれている必要があります。

ファイル

目的/説明

Program.cs

このサンプルのソース コードが含まれます。

SimpleWebApi.sln
SimpleWebApi.csproj
packages.config
AssemblyInfo.cs
App.config

このサンプルの標準 Microsoft Visual Studio 2015 ソリューション、プロジェクト、NuGet パッケージ構成、アセンブリ情報、およびアプリケーションの構成ファイルです。

次に、以下の手順を使用して、このサンプルを実行します。

  1. ソリューション ファイル、SimpleWebApi.sln を探しダブル クリックして、ソリューションを Visual Studio に読み込みます。

  2. [ソリューション エクスプローラー] で、[Program.cs] ファイルをダブルクリックし、エディターで開きます。

  3. Main メソッド内で //TODO コメントを探し、必須の接続文字列値を追加し、関連する行をコメント解除します。

  4. [SimpleWebApi] ソリューションを構築します。 これにより、見あたらないまたはアップグレードする必要がある必要なすべての NuGet パッケージは自動的にダウンロードされ、インストールされます。

  5. Visual Studio 内から [SimpleWebApi] プロジェクトを実行します。 すべてのサンプル ソリューションは、既定では、デバッグ モードで実行するように構成されています。

  6. 動作は展開の種類に応じて異なります。

    • オンラインおよび IFD 展開の場合、コンソール アプリケーションにより、ユーザーの資格情報とパスワードを入力する新しいウィンドウが開かれます。

    • 設置型展開の場合、コンソール アプリケーションにより、指定された Dynamics 365 アカウントのパスワードの入力が求められます。

    この情報を入力し、[Enter] を押します。

コード一覧

このファイルの最新のソースはサンプル ダウンロード パッケージにあります。

Program.cs

namespace Microsoft.Crm.Sdk.Samples
{
    /// <summary>
    /// A basic Web API client application for Dynamics 365 (CRM). This sample authenticates 
    /// the user and then calls the WhoAmI Web API function. 
    /// </summary>
    /// <remarks> 
    /// Prerequisites: 
    ///   -  To run this application, you must have a CRM Online or on-premise account. 
    ///   -  For CRM Online or Internet-facing deployments (IFD), the application must be registered  
    ///      with Azure Active Directory as described in this article: 
    ///      https://msdn.microsoft.com/en-us/library/dn531010.aspx
    ///   
    /// The WhoAmI Web API function is documented here: 
    ///    https://msdn.microsoft.com/en-us/library/mt607925.aspx
    /// </remarks>
    static class SimpleWebApi
    {
        //TODO: Uncomment then substitute your correct Dynamics 365 organization service 
        // address for either CRM Online or on-premise (end with a forward-slash).
        //private static string serviceUrl = "https://mydomain.crm.dynamics.com/myorg/";   // CRM Online
        //private static string serviceUrl = "https://<organization name>.<domain name>/";   // CRM IFD
        //private statics string serviceUrl = "http://myserver/myorg/";        // CRM on-premises

        //TODO: For an on-premises deployment, set your organization credentials here. (If
        // online or IFD, you can you can disregard or set to null.)
        private static string userAccount = "<user-account>";  //CRM user account
        private static string domain = "<server-domain>";  //CRM server domain

        //TODO: For CRM Online or IFD deployments, substitute your app registration values  
        // here. (If on-premise, you can disregard or set to null.)
        private static string clientId = "<app-reg-guid>";     //e.g. "e5cf0024-a66a-4f16-85ce-99ba97a24bb2"
        private static string redirectUrl = "<redirect-URL>";  //e.g. "https://localhost/SdkSample"

        static public void Main(string[] args)
        {
            //One message handler for OAuth authentication, and the other for Windows integrated 
            // authentication.  (Assumes that HTTPS protocol only used for CRM Online.)
            HttpMessageHandler messageHandler;
            if (serviceUrl.StartsWith("https://"))
            {
                messageHandler = new OAuthMessageHandler(serviceUrl, clientId, redirectUrl,
                         new HttpClientHandler());
            }
            else
            {
                //Prompt for user account password required for on-premise credentials.  (Better
                // approach is to use the SecureString class here.)
                Console.Write("Please enter the password for account {0}: ", userAccount);
                string password = Console.ReadLine().Trim();
                NetworkCredential credentials = new NetworkCredential(userAccount, password, domain);
                messageHandler = new HttpClientHandler() { Credentials = credentials };
            }
            try
            {
                //Create an HTTP client to send a request message to the CRM Web service.
                using (HttpClient httpClient = new HttpClient(messageHandler))
                {
                    //Specify the Web API address of the service and the period of time each request 
                    // has to execute.
                    httpClient.BaseAddress = new Uri(serviceUrl);
                    httpClient.Timeout = new TimeSpan(0, 2, 0);  //2 minutes

                    //Send the WhoAmI request to the Web API using a GET request. 
                    var response = httpClient.GetAsync("api/data/v8.1/WhoAmI",
                            HttpCompletionOption.ResponseHeadersRead).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        //Get the response content and parse it.
                        JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                        Guid userId = (Guid)body["UserId"];
                        Console.WriteLine("Your system user ID is: {0}", userId);
                    }
                    else
                    {
                        Console.WriteLine("The request failed with a status of '{0}'",
                               response.ReasonPhrase);
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayException(ex);
                throw;
            }
            finally
            {
                Console.WriteLine("Press <Enter> to exit the program.");
                Console.ReadLine();
            }
        }

        /// <summary> Displays exception information to the console. </summary>
        /// <param name="ex">The exception to output</param>
        private static void DisplayException(Exception ex)
        {
            Console.WriteLine("The application terminated with an error.");
            Console.WriteLine(ex.Message);
            while (ex.InnerException != null)
            {
                Console.WriteLine("\t* {0}", ex.InnerException.Message);
                ex = ex.InnerException;
            }
        }
    }

    /// <summary>
    ///Custom HTTP message handler that uses OAuth authentication thru ADAL.
    /// </summary>
    class OAuthMessageHandler : DelegatingHandler
    {
        private AuthenticationHeaderValue authHeader;

        public OAuthMessageHandler(string serviceUrl, string clientId, string redirectUrl,
                HttpMessageHandler innerHandler)
            : base(innerHandler)
        {
            // Obtain the Azure Active Directory Authentication Library (ADAL) authentication context.
            AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(
                    new Uri(serviceUrl + "api/data/")).Result;
            AuthenticationContext authContext = new AuthenticationContext(ap.Authority, false);
            //Note that an Azure AD access token has finite lifetime, default expiration is 60 minutes.
            AuthenticationResult authResult = authContext.AcquireToken(serviceUrl, clientId, new Uri(redirectUrl));
            authHeader = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
        }

        protected override Task<HttpResponseMessage> SendAsync(
                 HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            request.Headers.Authorization = authHeader;
            return base.SendAsync(request, cancellationToken);
        }
    }
}

関連項目

Web API Reference
Web API のサンプル
Microsoft Dynamics 365 Web API Helper Library (C#) の使用
Microsoft Dynamics 365 でユーザーを認証する

Microsoft Dynamics 365

© 2017 Microsoft. All rights reserved. 著作権