A day with .Net

My day to day experince in .net

SOAP Message inspector for SOAP WCF Web service proxy

Posted by vivekcek on October 31, 2012

I hope you know how to create a WCF proxy using SVCUTIL.EXE.
You can refer my old post ‘Create proxy of WCF web service with svcutil

Add the proxy class to your project and add reference to System.ServiceModel namespace.
use the below namespace’s in your project.

using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;

Now add a class MessageViewerInspector as a nested class.

internal class MessageViewerInspector : IEndpointBehavior, IClientMessageInspector
        {

            #region Properties
            public string RequestMessage { get; set; }
            public string ResponseMessage { get; set; }
            #endregion

            #region IEndpointBehavior Members
            public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
            {

            }

            public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
            {
                // adds our inspector to the runtime
                clientRuntime.MessageInspectors.Add(this);
            }

            public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
            {

            }

            public void Validate(ServiceEndpoint endpoint)
            {

            }
            #endregion

            #region IClientMessageInspector Members
            void IClientMessageInspector.AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
                this.ResponseMessage = reply.ToString();
            }

            object IClientMessageInspector.BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
            {
                this.RequestMessage = request.ToString();
                return null;
            }
            #endregion
        }

Now create your proxy object as below.

MessageViewerInspector inspector = new MessageViewerInspector();
ServiceSoapClient _Client=new ServiceSoapClient()
_Client.Endpoint.EndpointBehaviors.Add(inspector);

the inspector object have 2 properties ‘RequestMessage’ and ‘ResponseMessage’ contain SOAP request and response after you called any operations through proxy.

Advertisements

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