IClientMessageInspector – How to inspect and modify the message?

Posted on March 29, 2011 by

2


IClientMessageInspector allows to inspect or modify SOAP messages on the client side.

Here are some examples of usage for this extensibility point:

  • Message Validation -
    • Ensure the message is compliant with a certain schema
    • Validate its content or headers
  • Logging or Tracing
  • Manipulating the Message (For example: manipulate its headers)

Note: Parameters validation is done through the IParameterInspector and not through the IClientMessageInspector   (see http://wcfpro.wordpress.com/2010/12/21/iparameterinspector-how-to-inspect-arguments-and-return-values/)

The IClientMessageInspector interface contains two methods. The method BeforeSendRequest is called before the request is sent from the client, and the method AfterReceiveReply is called when the response from the server side is received by the client.

Both methods receive a reference to the Message object, allowing them to change its content.

public interface IClientMessageInspector
{
    void AfterReceiveReply(
        ref Message reply,
        object correlationState);

    object BeforeSendRequest(
        ref Message request,
        IClientChannel channel);
}

IClientMessageInspector  sample

The IClientMessageInspector is added to the MessageInspectors collection on the ClientRuntime object in the following way:

 

    public class MyBehavior : IEndpointBehavior
    {
        #region IEndpointBehavior Members

        public void AddBindingParameters(
            ServiceEndpoint endpoint,
            BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(
            ServiceEndpoint endpoint, 
            ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(new MyMessageInspector());
        }

        public void ApplyDispatchBehavior(
            ServiceEndpoint endpoint, 
            EndpointDispatcher endpointDispatcher)
        {
        }

        public void Validate(
            ServiceEndpoint endpoint)
        {
        }

        #endregion
    }

    #endregion

    #region MyMessageInspector

    public class MyMessageInspector : IClientMessageInspector
    {
        #region IClientMessageInspector Members

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

        public object BeforeSendRequest(
            ref Message request, 
            IClientChannel channel)
        {
            Console.WriteLine(
            "Sending the following request: '{0}'", request.ToString());
            return null;
        }

        #endregion
    }

About these ads
Posted in: WCF Extensions