次の方法で共有


OData v4 クライアント アプリを作成する (C#)

作成者: Mike Wasson

前のチュートリアルでは、CRUD 操作をサポートする基本的な OData サービスを作成しました。 次に、サービスのクライアントを作成してみましょう。

Visual Studio の新しいインスタンスを開始し、新しいコンソール アプリケーション プロジェクトを作成します。 [新しいプロジェクト] ダイアログで、[インストール済み]>[テンプレート]>[Visual C#]>[Windows デスクトップ] を選択し、[コンソール アプリケーション] テンプレートを選択します。 プロジェクトに「ProductsApp」という名前を付けます。

Screenshot of the new project dialog box, highlighting the path through the menu options, to create a new console application project.

Note

OData サービスを含む同じ Visual Studio ソリューションにコンソール アプリを追加することもできます。

OData クライアント コード ジェネレーターをインストールする

[ツール] メニューの [拡張機能と更新プログラム] を選択します。 [オンライン]>[Visual Studio ギャラリー] を選択します。 検索ボックスで、「OData クライアント コード ジェネレーター」を検索します。 [ダウンロード] をクリックして、VSIX をインストールします。 Visual Studio を再起動するように求められる場合があります。

Screenshot of the extensions and updates dialog box, showing the menu for downloading and installing the V S I X client code generator for O Data.

OData サービスをローカルで実行する

Visual Studio から ProductService プロジェクトを実行します。 既定では、Visual Studio はブラウザーを起動してアプリケーション ルートにアクセスします。 URI を書き留めます。これは次の手順で必要になります。 アプリケーションが実行されている状態のままにします。

Screenshot of the web browser's local host, showing the code of the Product Service project that is running on visual studio.

Note

両方のプロジェクトを同じソリューションに配置する場合は、デバッグせずに ProductService プロジェクトを実行してください。 次の手順では、コンソール アプリケーション プロジェクトの変更中に、サービスを実行し続ける必要があります。

サービス プロキシを生成する

サービス プロキシは、OData サービスにアクセスするためのメソッドを定義する .NET クラスです。 プロキシは、メソッド呼び出しを HTTP 要求に変換します。 T4 テンプレートを実行して、プロキシ クラスを作成します。

プロジェクトを右クリックします。 [追加]>[新しい項目] の順に選択します。

Screenshot of the solution explorer dialog box, showing the file path for adding a new item to the project, by highlighting the options in yellow.

[新しい項目の追加] ダイアログで、[Visual C# 項目]>[コード]>[OData クライアント] を選択します。 テンプレートに「ProductClient.tt」という名前を付けます。 [追加] をクリックし、セキュリティ警告をクリックします。

Screenshot of the new items product app settings window, showing the O Data client product template, and circling the name field below to add new name.

この時点で、エラーが発生しますが、無視してかまいません。 Visual Studio によってテンプレートが自動的に実行されますが、テンプレートには最初にいくつかの構成設定が必要です。

Screenshot of the error message window, showing one error tab and one warning tab, along with a detailed message of the error.

ProductClient.odata.config ファイルを開きます。Parameter 要素で、ProductService プロジェクトの URI を貼り付けます (前の手順)。 次に例を示します。

<Parameter Name="MetadataDocumentUri" Value="http://localhost:61635/" />

Screenshot of the product client O Data dot config file, showing an example of the U R I after being pasted in the parameter element.

テンプレートをもう一度実行します。 ソリューション エクスプローラーで、ProductClient.tt ファイルを右クリックし、[カスタム ツールの実行] を選択します。

テンプレートは、プロキシを定義する ProductClient.cs という名前のコード ファイルを作成します。 アプリを開発するときに、OData エンドポイントを変更する場合は、テンプレートをもう一度実行してプロキシを更新します。

Screenshot of the solution explorer window menu, highlighting the product client dot c s file that was created, which defines the proxy.

サービス プロキシを使用して OData サービスを呼び出す

ファイル Program.cs を開き、定型コードを次のように置き換えます。

using System;

namespace ProductsApp
{
    class Program
    {
        // Get an entire entity set.
        static void ListAllProducts(Default.Container container)
        {
            foreach (var p in container.Products)
            {
                Console.WriteLine("{0} {1} {2}", p.Name, p.Price, p.Category);
            }
        }

        static void AddProduct(Default.Container container, ProductService.Models.Product product)
        {
            container.AddToProducts(product);
            var serviceResponse = container.SaveChanges();
            foreach (var operationResponse in serviceResponse)
            {
                Console.WriteLine("Response: {0}", operationResponse.StatusCode);
            }
        }

        static void Main(string[] args)
        {
            // TODO: Replace with your local URI.
            string serviceUri = "http://localhost:port/";
            var container = new Default.Container(new Uri(serviceUri));

            var product = new ProductService.Models.Product()
            {
                Name = "Yo-yo",
                Category = "Toys",
                Price = 4.95M
            };

            AddProduct(container, product);
            ListAllProducts(container);
        }
    }
}

serviceUri の値を、前のサービス URI に置き換えます。

// TODO: Replace with your local URI.
string serviceUri = "http://localhost:port/";

アプリを実行すると、次のように出力されます。

Response: 201
Yo-yo 4.95 Toys