Getting the ServiceDescription for a WCF Service

Sometimes you may need to get at a service's ServiceDescription (WSDL) from a place where it is not normally accessible. One way to do so that I found is if you've enabled metadata publishing for your service, you can do something like this:

using System.ServiceModel;

using System.ServiceModel.Channels;

using System.ServiceModel.Description;

using WSDL = System.Web.Services.Description;

 

private WSDL.ServiceDescription GetServiceDescription()

{

   OperationContext context = OperationContext.Current;

   ServiceMetadataExtension mex =

      context.Host.Extensions.Find<ServiceMetadataExtension>();

   // find the wsdl

   foreach ( MetadataSection section in mex.Metadata.MetadataSections )

   {

      if ( section.Dialect == MetadataSection.ServiceDescriptionDialect

      {

         return (WSDL.ServiceDescription)section.Metadata;

      }

   }

   return null;

}

The only thing to watch out for is that the returned ServiceDescription object won't contain a Service element, but it's otherwise very usable!

Leave a comment

Your comment