Using IDispatchMessageInspector to get request's remote address

4.3k Views Asked by At

I'm trying to follow this blog post: http://blogs.msdn.com/b/carlosfigueira/archive/2011/04/19/wcf-extensibility-message-inspectors.aspx

My aim is to somehow get the remote address of the incoming request, but for some reason the address either is nowhere to be seen in any of the parameters, or is null.

Here's the interface I'm implementing:

public interface IDispatchMessageInspector
{
    object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext);
    void BeforeSendReply(ref Message reply, object correlationState);
}

The method I'm trying to get the remote address in is AfterReceiveRequest. I've checked both parameters request and channel. Also, it seems that channel.RemoteAddress is where it should be, but that property is null for some reason. The request parameter is also null, but I'm guessing that's because I'm doing a GET and not a POST.

Below is the signature of the method I'm invoking to test this out.

[OperationContract, WebGet( UriTemplate = "{*path}", ResponseFormat = WebMessageFormat.Json)]
string[] GetList(string path);
3

There are 3 best solutions below

0
On BEST ANSWER

Use OperationContext.Current.IncomingMessageHeaders.From

OR

(OperationContext.Current. IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty).Address

OR

HttpContext.Current.Request.UserHostAddress (BEWARE this one requires setting <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>)

1
On

The information will be in the request headers, found using:

WebHeaderCollection headers = WebOperationContext.Current.IncomingRequest.Headers;
0
On

Use this from IDispatchMessageInspector implementation:

var remoteEndpoint = request.Properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
var ipAddress = remoteEndpoint.Address;