Sunday, June 05, 2011

Dynamically updating WCF endpoint addresses in WSDL meta data

Introduction
I have already written some blog articles about WCF and how flexible and extensible it is. A lot of WCF its internal components can be extended or replaced by custom, user developed implementations. Not surprisingly, we can also hook into the WSDL meta data generation.
Recently I was in a situation were I had to develop a self hosted WCF service, but I did not know the target hosting server(s) address(es) upfront and it was impossible for me to change the address in the app.config before deployment. Because WCF requires an absolute address for self hosted services, I had to use localhost. This works fine and gives no issues when calling the service from another computer, but it has one important drawback: WCF will use the localhost address in the generated WSDL meta data. In order to fix this, I created a custom WCF behavior.

IWsdlExportExtension
We can hook into the WSDL meta data generation by implementing the interface IWsdlExportExtension. This interface contains 2 methods: ExportContract and ExportEndpoint. If the class also implements IContractBehavior, the method ExportContract will be invoked by the WCF pipeline and vice versa for IEndpointBehavior and ExportEndpoint.
Because I only wanted to modify the endpoint addresses, I only had to implement the interface IEndpointBehavior and the method ExportContract. I wanted this also as a service behavior, so I also implemented the interface IServiceBehavior and I also extended the behavior from Attribute. This way, the behavior can be easily injected into the WCF pipeline by annotating the service implementation class with the behavior.

The modification itself is very simple; every occurrence of localhost in the endpoint addresses is replaced by the DNS name of the host machine.

public class HostNameAddressBehavior : Attribute, IWsdlExportExtension, IEndpointBehavior, IServiceBehavior
{
    private readonly Regex addressRegex;
    private readonly string hostName;
    public HostNameAddressBehavior()
    {
        hostName = Dns.GetHostName();
        addressRegex = new Regex(@"^(?<scheme>[a-z\.]+)://localhost(?<path>.*)",
            RegexOptions.IgnoreCase);
    }
    public void ExportEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext context)
    {
        // Overwrite the address in the service meta data
        EndpointAddress address = context.Endpoint.Address;
        string absoluteUri = address.Uri.AbsoluteUri;
        Match m = addressRegex.Match(absoluteUri);
        if (m.Success)
        {
            string scheme = m.Groups["scheme"].Value;
            string path = m.Groups["path"].Value;
            // Update base address
            Uri newAbsoluteUri = new Uri(string.Format("{0}://{1}{2}",
                scheme, hostName, path));
            context.Endpoint.Address = new EndpointAddress(newAbsoluteUri,
                address.Identity, address.Headers, address.GetReaderAtMetadata(),
                address.GetReaderAtExtensions());
        }
    }