tags:

views:

42

answers:

1

Hey, how do you get the IP address of the person making a request in something like the following:

    [ServiceContract]    
    [AspNetCompatibilityRequirements(RequirementsMode = 
    AspNetCompatibilityRequirementsMode.Required)]    
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]        
    public partial class UsersService
    {                          
        [WebInvoke(UriTemplate = "", Method = "PUT")]        
        public User AddNewUser(User newUser)
        {            
            // code goes here including GETTING AN IP??
        }

Thanks!

+1  A: 

Inside AddNewUser use following snippet:

OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpointProperty =
  messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

RemoteEndpointMessageProperty instance offers Address and Port properties.

Ladislav Mrnka
The problem is that unless something has changed in .Net 4, it is a real pain to get hold of OperationContext when using WebHttpBinding. I was able to do by creating a MessageInspector, but it requires quit a bit of hoop jumping.
Darrel Miller
I'm not sure what do you mean by that. OperationContext has to be available in any WCF call even if it is REST service exposed on WebHttpBinding. I tested it in WCF 4 and it works.
Ladislav Mrnka
In .Net 3.5 with WebHttpBinding you could access WebOperationContext, but OperationContext was not available directly. I'm happy to hear they have fixed that in 4.0.
Darrel Miller
Perfect, works like a charm :)
nextgenneo