WCF サービスを利用する基本的な方法

この資料では 「単純な WCF ウェブサービスの実装例」 で作成したウェブサービスを利用するクライアントを作成します。 下記の方法を試す前に、メタデータが正しく発行されていること を確認して、 必要に応じて環境を修正してください。

さて、準備はできましたでしょうか。

ウェブサービスを利用する方法 ~ プロキシの作成

ウェブサービスを利用するには、プロキシと呼ばれるコードを作成します。

プロキシ (proxy) というのは基本的に "代理人" という意味で、"Web サービスの代理人" となるモジュールを指します。

まぁ、プロキシという言葉自体はコンピュータサイエンス、プログラミングの世界ではいろんな意味で登場するのですが、 ウェブサービスという話の中では、そんな風に出てくるわけです。

プロキシはあなたのプログラム内で、遠隔にある Web サービスを呼出すときの窓口となります。 Web サービスの foo メソッドを呼びたいときは、プロキシの foo メソッドを呼出します。 すると、プロキシはその背後でネットワークを越えた呼び出しを行い、その結果を取得して、元の呼出し元に結果を返します。

このようにして、ネットワークやらなにやらといった、ネットワーク越しのサービス提供であることのややこしさが減らせることになります。

ちなみに、Web サービスの通信に使われるプロトコルは SOAP over HTTP が主流で、 Web サービスが Java だろうと、WCF だろうと、変わらない統一された方法でアクセスできるので便利です。

さて、では実際にそのプロキシコードを生成して、プログラムから利用してみましょう。

プロキシの作成

実はプロキシの生成は簡単です。WCF ウェブサービスを作成すると、次のようにモロに作成方法が表示されます。

この通りにコマンドをたたいてみましょう。

>svcutil http://keisukeo-hp:8889/CalcService/CalcService.svc?wsdl
Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version 4.0.30319.1]
Copyright (c) Microsoft Corporation.  All rights reserved.

Attempting to download metadata from 
'http://keisukeo-hp:8889/CalcService/CalcService.svc?wsdl' 
using WS-Metadata Exchange or DISCO.

Generating files...
C:\src\test\CalcClient\Calc.cs
C:\src\test\CalcClient\output.config

>

尚、.NET Framework のバージョン毎にそれぞれのコマンドセットがありますが、 .NET Framework 4 版のコマンドは SDK 以下ののディレクトリ NETFX 4.0 Tools (例: C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools など) にありますので、 コマンドでパスが通ってなかったらパスを通して置いてください。

さて、上記のコマンドをたたいた結果、Calc.cs と output.config が作成されました。 この Calc.cs がプロキシコードです。そして、output.config がエンドポイントを定義するアプリケーション設定ファイルになります。

次のコードを test.cs として保存します。

class Test
{
     static void Main()
     {
          int i = 1;
          int j = 2;
          int z;
          
          CalcClient client = new CalcClient();
          
          z = client.Add(i,j);
          System.Console.WriteLine("i + j = {0}", z);
          
          client.Close();
     }
}

次のコマンドでビルドします。

> csc Calc.cs test.cs

この結果として、test.exe が作成されます。 そこで、svcutil の出力結果の output.config を test.exe.config にリネームします。

これで準備完了です。test.exe を実行しましょう。
次のように表示されたら成功です。

> test.exe
i + j = 3

発生しうる例外

もし次のように表示されたら、エンドポイントが正しく設定されていないので、 設定ファイルが正しく配置されているか確認してください。

> test.exe

Unhandled Exception: System.InvalidOperationException: 
Could not find default endpoint element that references contract 
'ICalc' in the ServiceModel client configuration section.
This might be because no configuration file was found 
for your application, or because no endpoint element matching this contract 
could be found in the client element.
   at System.ServiceModel.Description.ConfigLoader.LoadChannelBehaviors(
ServiceEndpoint serviceEndpoint, String configurationName)
   at System.ServiceModel.ChannelFactory.ApplyConfiguration(
String configurationName, Configuration configuration)
   at System.ServiceModel.ChannelFactory.ApplyConfiguration(
String configurationName)
   at System.ServiceModel.ChannelFactory.InitializeEndpoint(
String configurationName, EndpointAddress address)
   at System.ServiceModel.ChannelFactory`1..ctor(
String endpointConfigurationName, EndpointAddress remoteAddress)
   at System.ServiceModel.EndpointTrait`1.CreateSimplexFactory()
   at System.ServiceModel.EndpointTrait`1.CreateChannelFactory()
   at System.ServiceModel.ClientBase`1.CreateChannelFactoryRef(
EndpointTrait`1 endpointTrait)
   at System.ServiceModel.ClientBase`1.InitializeChannelFactoryRef()
   at System.ServiceModel.ClientBase`1..ctor()
   at Test.Main()

また、次の場合は Web サービスが現在利用できない(接続できない)場合です。 Web サービスが利用可能かどうか確認しましょう。

> test

Unhandled Exception: System.ServiceModel.EndpointNotFoundException: 
Could not connect to http://keisukeo-hp:8889/CalcService/CalcService.svc. 
TCP error code 10061: No connection could be made because the target 
machine actively refused it 192.168.1.30:8889.  
---> System.Net.WebException: Unable to connect to the remote server 
---> System.Net.Sockets.SocketException: No connection could be made 
because the target machine actively refused it 192.168.1.30:8889
...

ここまでお読みいただき、誠にありがとうございます。SNS 等でこの記事をシェアしていただけますと、大変励みになります。どうぞよろしくお願いします。

© 2024 ASP.NET 入門