How to: Publish Metadata for a Service Using Code 

You can publish metadata for a service in two ways: declaratively in a configuration file or imperatively in code. This topic shows you how to publish metadata in code.

To publish metadata in code

  1. Instantiate a ServiceHost object by passing in the service type and the base address:

    C#

    Copy Code

    ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress);
    
  2. Check to see whether the service host already contains a ServiceMetadataBehavior and, if so, set HttpGetEnabled to true and HttpGetUrl to an appropriate URL. If the service host does not already have a ServiceMetadataBehavior, set the appropriate properties and add the ServiceMetadataBehavior to the service host's behaviors collection:

    C#

    Copy Code

    ServiceMetadataBehavior smb = serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
    if (smb != null)
    {
        smb.HttpGetEnabled = true;
        smb.HttpGetUrl = mexAddress;
    }
    else
    {
        smb = new ServiceMetadataBehavior();
        smb.HttpGetEnabled = true;
        smb.HttpGetUrl = mexAddress;
        serviceHost.Description.Behaviors.Add(smb);
    }
    
  3. Add the metadata exchange endpoint:

    C#

    Copy Code

    ServiceEndpoint se = serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), new WSHttpBinding(), mexAddress);
    
  4. Use Internet Explorer to browse to the base address of the service and verify that the metadata publishing has been turned on. If not, you will see a message at the top of the resulting page that says: "Metadata publishing for this service is currently disabled."

See Also

Tasks

How to: Host a WCF Service in a Managed Application

Concepts

Metadata Architecture Overview
Using Metadata

Other Resources

Self-Host

Source: How to: Publish Metadata for a Service Using Code

posted on 2007-03-11 18:36  Joey Liang  阅读(260)  评论(0编辑  收藏  举报