Search code examples
c#wcfidispatchmessageinspector

Using IDispatchMessageInspector to get request's remote address


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);

Solution

  • 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"/>)