Posted by: Cirilo Meggiolaro | 12/20/2008

Tip of the day #67 – Exposing services metadata with WCF

Did you know that is possible to expose metadata from your WCF (Windows Communication Foundation) service?

Yes, it is possible and easy to implement. The metadata is exposed through HTTP-GET and you need to perform two steps to accomplish that:

Using a configuration file to define the metadata endpoint

       <service name=CustomerServicebehaviorConfiguration=CustomerMexGet>
         <endpoint address=http://localhost:8000/CustomerService/
         <endpoint address=mex
         <behavior name=CustomerMexGet>
           <serviceMetadata httpGetEnabled=True/>

Defining the metadata endpoint programmatically

Define a metadata endpoint programmatically has the same steps than the definition via config file. You are going to create the metadata behavior and the endpoint. The process is straightforward for those that have any experience with WCF. The following code performs the same tasks than the config used previously:

ServiceHost host = new ServiceHost(typeof(CustomerService));

/// Declares a ServiceMetadataBehavior object.
/// Tries to find an existing ServiceMetadataBehavior
/// in the behaviors collection.

ServiceMetadataBehavior metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();

/// If the metadata behavior does not exist
/// creates a new one and add to the Behaviors
/// collection from the host.
if (metadataBehavior == null)
    metadataBehavior = new ServiceMetadataBehavior();

    /// Enables HTTP-GET to retrieve the metadata
    metadataBehavior.HttpGetEnabled = true;

    /// Adds the metadata exchange behavior to the behaviors collection.

/// Defines the regular binding
BasicHttpBinding httpBinding = new BasicHttpBinding();

/// Adds the regular endpoint
host.AddServiceEndpoint(typeof(ICustomerService), httpBinding, http://localhost:8000/CustomerService/&#8221;);

/// Add the metadata endpoint
host.AddServiceEndpoint(“IMetadataExchange”, MetadataExchangeBindings.CreateMexHttpBinding(), “mex”);

Leave a Reply

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

You are commenting using your 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


%d bloggers like this: