Ehsan Ghanbari

Experience, DotNet, Solutions

Custom soap header in WCF

In WCF, by using the MessageHeader attribute, you can add a soap header for messages:


 

 [MessageContract]

    public class SoapTest

    {

        [MessageHeader]

        public int Id { get; set; }

    }

 

And now by implementing the IClientMessageInspector members, you can add your own custom message header in BeforeSendRequest method:

 

 

  public class MessageInspector : IClientMessageInspector

    {

        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)

        { 

        }

 

        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)

        {

            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);

            request = buffer.CreateMessage();

            Console.WriteLine("Sending:\n{0}", buffer.CreateMessage().ToString());

            return null;

        }

    }

 

Rather than the solution above, there is another library named wcfextrasplus which is more straightforward. Look at the class below:

   

 public partial class SoapHeadersSampleClient

    {

        public Header MyCustomHeader

        {

            get

            {

                return InnerChannel.GetHeader<Header>("CustomHeader");

            }

            set

            {

                InnerChannel.SetHeader("CustomHeader", value);

            }

        }

    }

 

And now you can use the CustomHeader like this:

 

  public void TestHeaders()

        {

            var client = new SoapHeadersSampleClient() { MyCustomHeader = new Header() { Value = "Test" } };

 

             var result = client.In();

           

            client.Out("Testing output");

            result = client.MyCustomHeader.Value;

        }

 

but I personally like the first solution! 



Duplex Message Exchange Pattern in WCF

There are 3 message exchange patterns (MEP) in the WCF: Request/Response, One Way and Duplex - I'm going to talk about the Duplex pattern in this post. In duplex pattern, Both the client and the server can send messages to each other independently. This can be used by request/Response messaging pattern too but In the request/Response and one-way message exchange patterns, the communication is initiated by the client application, but in the duplex message exchange pattern, both the client and the service can initiate the communication. If a client calls a long-running method on a service, it's not a good idea that the client waits until receiving the response, so we can use Duplex pattern to solve this. It will provide the client to get the response right after completing the request operation.  In other words, the duplex pattern is consists of two one way pattern. You can use this pattern when you want the service to send a message or alert to the client after the client has called the service.

 

Take a look at this piece of code, all you need to do to achieve this pattern:

 

   public interface IDuplexResponse
    {
        string DuplexMethod(string parameter);
    }

    [ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IDuplexResponse))]
    public interface IDuplexService
    {
        [OperationContract]
        string ReturnSomeValue(string value);
    }

 

Let's consider Another example, this is a little bit closer to real-world applications, create the IAccountService interface with this definition:

 

    [ServiceContract(SessionMode = SessionMode.Required,
                 CallbackContract = typeof(IAccountServiceCallback))]
    public interface IAccountService
    {
        [OperationContract(IsOneWay = true)]
        void AddTo(double amount);
     
        [OperationContract(IsOneWay = true)]
        void Tax(double amount);
    }

 

And Create the IAccountServiceCallback interface like this(duplex or two way)

 

    public interface IAccountServiceCallback
    {
        [OperationContract(IsOneWay = true)]
        void Equals(double result);
    }

 

Now let's implement the AccountService class

 

    public class AccountService :IAccountService
    {
        private IAccountServiceCallback _accountServiceCallback = null;

        public AccountService()
        {
            _accountServiceCallback = OperationContext.Current.GetCallbackChannel<IAccountServiceCallback>();
        }


        public void AddTo(double amount)
        {
            throw new NotImplementedException();
        }

        public void Tax(double amount)
        {
            throw new NotImplementedException();
        }
    }

 

Got it!?

ServiceContract and OperationContract attributes allow you to generate the service contract and also it's worth to say that The difference between Request-response and Duplex pattern is that Request-response pattern requires the response on same communication channel whereas Duplex creates the separate communication channel to return a response to the client.

 



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in asp.net MVC4
How to use PagedList In asp.net MVC
Redis as a cache server
Domain driven design VS model driven architecture
What's the DDD-lite?
Multiple submit buttons in asp.net MVC