21

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!

Luke Belbina
  • 5,708
  • 12
  • 52
  • 75

1 Answers1

39

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
  • 360,892
  • 59
  • 660
  • 670
  • 1
    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 Aug 28 '10 at 12:42
  • 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 Aug 28 '10 at 12:58
  • 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 Aug 29 '10 at 17:55
  • Somehow I am getting the server name where I am hosting my service. I want to get client details – Ziggler Nov 16 '19 at 00:10