How to use IDispatchMessageInspector in a WCF Service?

Didaxis picture Didaxis · Jun 13, 2014 · Viewed 20.9k times · Source

I am trying to use IDispatchMessageInspector in a WCF service implementation to access custom header values.

Something like:

public class MyService : IMyService
{
    public List<string> GetNames()
    {
        var headerInspector = new CustomHeaderInspector();

        // Where do request & client channel come from?
        var values = headerInspector.AfterReceiveRequest(ref request, clientChannel, OperationContext.Current.InstanceContext);            
    }
}

I've implemented my own IDispatchMessageInspector class.

public class CustomHeaderInspector : IDispatchMessageInspector
{
    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        var prop = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
        var userName = prop.Headers["Username"];

        return userName;
    }
}

How do I pass

  • System.ServiceModel.Channels.Message and

  • System.ServiceModel.IClientChannel

to AfterReceiveRequest called from the service implementation?

EDIT:

Many articles like this one or this one, give examples on how to implement your own ServiceBehavior. So your service implementation looks like this:

[MyCustomBehavior]
public class MyService : IMyService
{
    public List<string> GetNames()
    {
        // Can you use 'MyCustomBehavior' here to access the header properties?
    }
}

So with this, can I access MyCustomBehavior somehow within the service operation method to access custom header values?

Answer

Peter picture Peter · Jun 16, 2014

You have to configure the

<extensions>
  <behaviorExtensions>
    <add 
      name="serviceInterceptors" 
      type="CustomHeaderInspector , MyDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
    />
  </behaviorExtensions>
</extensions>

Then the extension will be handled in your WCF stack. The service itself has no notion of the serviceInterceptors and you do not have to do something like in your first code block. The WCF stack will inject you Inspector.

MSDN: system.servicemodel.dispatcher.idispatchmessageinspector