.NET Zone is brought to you in partnership with:

Yaron is a Microsoft MVP in the Connected System Developer realm. Yaron authors the successful Web Services 2.0 blog, in which he helps the community with some of his favorite topics: Web services, security and interoperability. Yaron is also an architect in HP. Yaron is a DZone MVB and is not an employee of DZone and has posted 23 posts at DZone. You can read more from them at their website. View Full User Profile

WCF Trick: Dynamically Change Proxy Address

06.30.2012
| 2511 views |
  • submit to reddit
It is quite common to have a few service environments, for example one for testing and one for production. One way to switch a Wcf client from one environment to another is by changing the address in app.config:

<endpoint address="http://localhost/Service.svc" ... />

However sometime we need to dynamically change the address from code due to some logic.
The naive approach would be to do something like this:

MyService client = new MyService("WSHttpBinding_MyService",
        "http://new_server/Service.svc")

The reason this is naive is that app.config may contain additional information on the endpoint, namely its identity and headers:

<endpoint address="http://localhost/Service.svc" Name="WSHttpBinding_MyService" ...>
   <identity>
     <dns value="ServerIdentity"/>
   </identity>
</endpoint>

when we create the proxy with a different endpoint in the constructor we override the identity information. This may result in this error:

Identity check failed for outgoing message. The expected DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'ServerIdentity'. If this is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'ServerIdentity' as the Identity property of EndpointAddress when creating channel proxy

The solution
Create the proxy normally. Then separately assign the new endpoint address keeping the identity and header values:
proxy.Endpoint.Address = new EndpointAddress(
    new Uri("http://new_server/Service.svc"),
    proxy.Endpoint.Address.Identity,
    proxy.Endpoint.Address.Headers);
Published at DZone with permission of Yaron Naveh, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)