ここでは、カスタム WS-Metadata Exchange バインディングを構成する方法を説明します。 Windows Communication Foundation (WCF) には、4 つのシステム定義のメタデータ バインディングがありますが、どのバインディングでもメタデータを公開できます。 ここでは、wsHttpBinding を使用してメタデータを公開する方法を示します。 このバインディングでは、メタデータをセキュリティで保護して公開することができます。 ここに示すコードは、「はじめに」に基づいています。
構成ファイルの使用
サービスの構成ファイルで、
serviceMetadataタグを含んだサービス動作を追加します。<behaviors> <serviceBehaviors> <behavior name="CalculatorServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> </behavior> </serviceBehaviors> </behaviors>この新しい動作を参照する
behaviorConfiguration属性をサービス タグに追加します。<service name="Microsoft.ServiceModel.Samples.CalculatorService" behaviorConfiguration="CalculatorServiceBehavior" />メタデータ エンドポイントを追加し、アドレスに mex、バインディングに
wsHttpBinding、コントラクトに IMetadataExchange をそれぞれ指定します。<endpoint address="mex" binding="wsHttpBinding" contract="IMetadataExchange" />Metadata Exchange エンドポイントが適切に動作することを確認するには、クライアントの構成ファイルにエンドポイント タグを追加します。
<endpoint name="MyMexEndpoint" address="http://localhost:8000/servicemodelsamples/service/mex" binding="wsHttpBinding" contract="IMetadataExchange"/>クライアントの Main() メソッドで、新しい MetadataExchangeClient インスタンスを作成し、その ResolveMetadataReferences プロパティを
trueに設定し、GetMetadata を呼び出して返されるメタデータのコレクションを反復処理します。string mexAddress = "http://localhost:8000/servicemodelsamples/service/mex"; MetadataExchangeClient mexClient = new MetadataExchangeClient("MyMexEndpoint"); mexClient.ResolveMetadataReferences = true; MetadataSet mdSet = mexClient.GetMetadata(new EndpointAddress(mexAddress)); foreach (MetadataSection section in mdSet.MetadataSections) Console.WriteLine("Metadata section: " + section.Dialect.ToString());
コードによる構成
WSHttpBinding バインディングのインスタンスを作成します。
WSHttpBinding binding = new WSHttpBinding();ServiceHost インスタンスを作成します。
ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress);サービス エンドポイントと ServiceMetadataBehavior インスタンスを追加します。
serviceHost.AddServiceEndpoint(typeof(ICalculator), binding, baseAddress); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; serviceHost.Description.Behaviors.Add(smb);前に作成した WSHttpBinding を指定する Metadata Exchange エンドポイントを追加します。
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), binding, mexAddress);Metadata Exchange エンドポイントが適切に動作することを確認するには、クライアントの構成ファイルにエンドポイント タグを追加します。
<endpoint name="MyMexEndpoint" address="http://localhost:8000/servicemodelsamples/service/mex" binding="wsHttpBinding" contract="IMetadataExchange"/>クライアントの Main() メソッドで、新しい MetadataExchangeClient インスタンスを作成し、その ResolveMetadataReferences プロパティを
trueに設定し、GetMetadata を呼び出して返されるメタデータのコレクションを反復処理します。string mexAddress = "http://localhost:8000/servicemodelsamples/service/mex"; MetadataExchangeClient mexClient = new MetadataExchangeClient("MyMexEndpoint"); mexClient.ResolveMetadataReferences = true; MetadataSet mdSet = mexClient.GetMetadata(new EndpointAddress(mexAddress)); foreach (MetadataSection section in mdSet.MetadataSections) Console.WriteLine("Metadata section: " + section.Dialect.ToString());