Get WCF Service Metadata on client application


Sometimes the client needs to programmatically verify whether a particular endpoint supports a particular contracts. Suppose Application administrator deployed application but it was pointing to development environment or some other address. If this feature implemented in application then he can get to know there is difference in service contracts or endpoints. He can then point to correct endpoints to run properly. This feature can reduce unnecessary diagnosis of errors on production system.

In order to support this feature client application should able to fetch metadata of service. This is not valid in case of netTcpBinding.

Metadata Processing

The metadata may be available either in special metadata exchange endpoints (if the service supports them), or over the HTTP-GET protocol. When you use HTTP-GET, the address of the metadata exchange is the HTTP-GET address suffixed by ?wsdl.

WCF Service

I hosted wcf service with HttpGetEnabled=”true” configuration. This is configuration on service side.

<?xml version="1.0"?>
<configuration>
 
  <system.web>
   </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8045/MarketService"
            httpGetBinding="webHttpBinding" httpGetBindingConfiguration="" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
      <service name="MyService">
        <endpoint address="net.tcp://localhost:8000/MyService" binding="netTcpBinding"
          name="tcpendpoint" contract="IMarketDataProvider" />
        <endpoint address="http://localhost:8045/marketservice" binding="basicHttpBinding"
          bindingConfiguration="httpbinding" name="httpservicepint" contract="MarketApi.IMarketDataProvider" />
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="httpbinding" />
      </basicHttpBinding>
      <netTcpBinding>
        <binding name="tcpbinding" transactionFlow="true" />
      </netTcpBinding>
    </bindings>
  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

This service is running on two bindings : tcpbinding and httpbinding with endpoints address net.tcp://localhost:8000/MyService" and http://localhost:8045/marketservice.

<serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8045/MarketService"
httpGetBinding="webHttpBinding" httpGetBindingConfiguration="" />

This configuration ensure that service metadata should be exposed and can be get via httpGetUrl. So wsdl will be available on http://localhost:8045/MarketService?wsdl address.

Service Host Code

 class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8045/MarketService");
            using (var productHost = new ServiceHost(typeof(MarketDataProvider)))
            {
                ServiceEndpoint productEndpoint = productHost.AddServiceEndpoint(
			typeof(IMarketDataProvider), new NetTcpBinding(), 
			"net.tcp://localhost:8000/MarketService");
                ServiceEndpoint producthttpEndpoint = productHost.AddServiceEndpoint(
			typeof(IMarketDataProvider), new BasicHttpBinding(), 
			"http://localhost:8045/MarketService");

                productHost.Open();
                Console.WriteLine("The Market service is running and is listening on:");
                Console.WriteLine("{0} ({1})",
                  productEndpoint.Address.ToString(),
                  productEndpoint.Binding.Name);
                Console.WriteLine("{0} ({1})",
                  producthttpEndpoint.Address.ToString(),
                  producthttpEndpoint.Binding.Name);
                Console.WriteLine("\nPress any key to stop the service.");
                Console.ReadKey();
            }
        }


    }

 

Access Metadata on Client Side

MetadataExchangeClient class in System.ServiceModel.Description namespace uses for downloading service metadata on client.

Constructor on MetadataExchangeClient accepts endpoint address instance wrapping the metadata exchange address and enum which specify mode to use when downloading the metadata. It can be MetaDataExchange or HttpGet.

Here is code which extract metadata information:

	
	  static void GetMetadata()
        {
            Uri mexAddress = new Uri("http://localhost:8045/marketservice");
            var mexClient = new MetadataExchangeClient(mexAddress, 
		MetadataExchangeClientMode.HttpGet);
            MetadataSet metadata = mexClient.GetMetadata();
            MetadataImporter importer = new WsdlImporter(metadata);
            ServiceEndpointCollection endpoints = importer.ImportAllEndpoints();

            foreach (var end in endpoints)
                Console.WriteLine("Endpoints on server {0}", end.Address);
            
            ContractDescription description =
            ContractDescription.GetContract(typeof(IMarketDataProvider));
            bool contractSupported = endpoints.Any(endpoint =>
            endpoint.Contract.Namespace == description.Namespace &&
            endpoint.Contract.Name == description.Name);

            if (!contractSupported)
                throw new Exception("Not supported service contracts");

        }

Endpoints can also be accessed with MetadataResolver class.

 ServiceEndpointCollection endpoints =  	
	   MetadataResolver.Resolve(typeof(IMarketDataProvider),
            mexAddress, MetadataExchangeClientMode.HttpGet);

This way you can access service metadata on client side to verify about about endpoints, service contracts.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: