Inspecting Messages in WCF

In WCF (Windows Communication foundation)  you can inpect the messages before sending reply and recieves client request through IDispatchMessageInspector interface. This helps the developer to investigate the message and log somewhere when needed.

In this post i will show the way of implementing IDispatchMessageInspector interface and how it can be applied in the custom behavior extension and configured for that Service behavior.

First of all you have to create a Message inspector class and implement the interface i.e. IDispatchMessageInspector. IDispatchMessageInspector interface provides two methods namely AfterReceiveRequest and BeforeSendReply which you can implement in the implementor class and inspect the messages. As the method named AfterRecieveRequest is called when the request came from the client and BeforeSendReply is called before the service sends the message back to client.

Below code snippet shows the class that implements IDispatchMessageInspector interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.Diagnostics.Eventing;
namespace WCFMain
{
    public class MessageInspector :  IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref Message request, 
          System.ServiceModel.IClientChannel channel, 
          System.ServiceModel.InstanceContext instanceContext)
        {
            Logger.WriteLogEntry("Inside the AfterRecieveRequest");
            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            Logger.WriteLogEntry("Inside Before Send Reply");
        }
    }
}

Inorder to add this Message Inpector we have to create a custom behavior extension class that derived from BehaviorExtensionElement and implements either IServiceBehavior or IEndpointBehavior. In WCF you can either add behavior at Service level or Endpoint level. In this example i will implement IServiceBehavior.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
namespace WCFMain
{
    public class MessageBehaviourExtension : BehaviorExtensionElement, IServiceBehavior
    {

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            Logger.WriteLogEntry("Inside the ApplyClientBehavior");
        }

        public override Type BehaviorType
        {
            get { return typeof(MessageBehaviourExtension); }
        }

        protected override object CreateBehavior()
        {
            return this;
        }

        public void AddBindingParameters(ServiceDescription serviceDescription, 
         System.ServiceModel.ServiceHostBase serviceHostBase, 
         System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, 
         BindingParameterCollection bindingParameters)
        {
            Logger.WriteLogEntry("Inside the AddBindingParameters");
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, 
         System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            Logger.WriteLogEntry("Inside Apply Dispatch Behavior");
            for (int i = 0; i < serviceHostBase.ChannelDispatchers.Count; i++)
            {
                ChannelDispatcher channelDispatcher = serviceHostBase.ChannelDispatchers[i] as ChannelDispatcher;
                if (channelDispatcher != null)
                {
                    foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
                    {
                        MessageInspector inspector = new MessageInspector();
                        endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
                    }
                }
            }
        }

        public void Validate(ServiceDescription serviceDescription, 
          System.ServiceModel.ServiceHostBase serviceHostBase)
        {

        }
    }
}

In the above snippet if you see that i have add the custom message inspector object for each endpoints defined for the service. So when the WCF engine calls this method it will add the message inspector for all endpoints defined in the service configuration.

Now, in the web.config file at server side you have to add following entries to configure this custom behavior extension and specify in the service behavior.

Advertisements

4 thoughts on “Inspecting Messages in WCF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s