IDispatchMessageInspector –How to change the message on the server side?

Posted on May 4, 2011 by

0


IDispatchMessageInspector allows to validate and modify the Message on the server side (similar to IClientMessageInspector, which is added on the client).

It’s interface allows you to interfere with the request Message before it arrives to the server, and with the response Message before it is sent to the client.

The IDispatchMessageInspector interface contains the following methods:

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

Here are some example for cases where you may use your custom IDispatchMessageInspector :

1. For adding logging and tracing every time a request Message arrives to the server, and every time a response Message is sent to the client.

2. For different types of validation, such as : validate the SOAP Message, validate the Http headers or validate the SOAP headers.

3. Modify the Soap Message (both AfterReceiveRequest and BeforeSendReply receive a reference to the Message object and can change it). For example: Update the version of the service

IDispatchMessageInspector  Sample

In this sample, we use the IDispatchMessageInspector to add logging capabilities to our service.

The IDispatchMessageInspector  is added through the IEndpointBehavior on the endpointDispatcher object.

  class MyServerMessageInspector : IEndpointBehavior, IDispatchMessageInspector
    {
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
        }

        public void Validate(ServiceEndpoint endpoint)
        {
        }
        
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            Console.WriteLine("Received the following request: '{0}'", request.ToString());
            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            Console.WriteLine("Sending the following reply: '{0}'", reply.ToString());
        }
    }

Advertisements
Posted in: WCF Extensions