Gaz
Gaz

Reputation: 4154

Obtaining client IP address in WCF 3.0

Apparently you can easily obtain a client IP address in WCF 3.5 but not in WCF 3.0. Anyone know how?

Upvotes: 82

Views: 64994

Answers (3)

Gaz
Gaz

Reputation: 4154

It turns out you can, so long as (a) your service is being hosted in a Web Service (obviously) and (b) you enable AspNetCompatibility mode, as follows:

    <system.serviceModel>
            <!-- this enables WCF services to access ASP.Net http context -->
            <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
...
    </system.serviceModel>

And then you can get the IP address by:

HttpContext.Current.Request.UserHostAddress

Upvotes: 36

Paul Mrozowski
Paul Mrozowski

Reputation: 6734

This doesn't help you in 3.0, but I can just see people finding this question and being frustrated because they are trying to get the client IP address in 3.5. So, here's some code which should work:

using System.ServiceModel;
using System.ServiceModel.Channels;

OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint =
    prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string ip = endpoint.Address;

Upvotes: 152

jangofetta
jangofetta

Reputation:

You can if you are targeting .NET 3.0 SP1.

OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string ip = endpoint.Address;

Credits: http://blogs.msdn.com/phenning/archive/2007/08/08/remoteendpointmessageproperty-in-wcf-net-3-5.aspx

Reference: http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.remoteendpointmessageproperty.aspx

Upvotes: 16

Related Questions