Dan Rigsby - Coding Up Style

Developer.Speaker.Blogger

Get the Service Endpoint address a Client is accessing in WCF

Posted by Dan Rigsby on May 25th, 2008

In a previous post I talked about how to get the address of a client accessing a WCF service.  I got a few questions after this asking how you would get the endpoint address of the service that the client is accessing?  A single service could have multiple endpoints, and when a client comes into the service you may branch the logic slightly depending on how they are accessing the data.  For instance, you might have a separate endpoint that is exposed outside of your network for external customers, and may want to restrict the amount of data they can access through a method. Or maybe if the client is using “Http” you might want to return back less data than if the client is using “Tcp”.

Getting the service endpoint address is actually much easier then getting the address of the client.  You just need to look at the LocalAddress on the Channel of the current Operation Context in the method:

OperationContext.Current.Channel.LocalAddress

Here is an example of a method that branches its results based on the schema (http, tcp, etc) of the endpoint that a client is accessing:

public List<Customer> GetCustomers()
{
    var customers = new List<Customer>();

    if (OperationContext.Current.Channel.LocalAddress.Uri.Scheme == "http")
    {
        // TODO: Get partial customer objects
    }
    else
    {
        // TODO: Get full customer objects
    }

    return customers;
}

3 Responses to “Get the Service Endpoint address a Client is accessing in WCF”

  1. Dew Drop - May 27, 2008 | Alvin Ashcraft's Morning Dew Says:

    [...] Get the Service Endpoint Address a Client Is Accessing in WCF (Dan Rigsby) [...]

  2. Mike Says:

    Thanks Dan!  Im wondering, can you use the same technique to determine the contract used to make the call?  I have a service in which one contract inherits from the other and when using the ChannelFactory to make my calls, I would like the service to determine if the base or child made the call.

  3. Luigi Says:

    I was wondering if this functionality can be used inside a factory within a CreateServiceHost override? I tried it, and I’m getting a null reference. Any ideas? I have multiple identites for a web site and I need to know which the user has chosen so that I can return the correct base address. Thanks.

    Luigi

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>