Decoding messages in WCF Data Services

Recently I had to solve an interesting problem while working with WCF Data Services and how to decode an incoming WCF message so I can do something useful with its content.

Let’s say that you have an already configured Data Service and you intercept the message using some sort extension/interceptors in WCF.

Here is an example of such function:

 

private static string DecodeMessage(ref Message message)

{

    if (message.IsEmpty)

         return null;

 

    using (MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue))

    {

        Message copy = buffer.CreateMessage();

        using (MemoryStream ms = new MemoryStream())

        {

           copy.Properties.Encoder.WriteMessage(copy, ms);

           ms.Flush();

           message = buffer.CreateMessage();

           return Encoding.UTF8.GetString(ms.ToArray());                       

        }

    }

}

As you can notice, after some basic message validation, we create a copy of the message to avoid changing the state of the original message which is typically passed by reference. Then we write all the content to MemoryStream which is handy for read/write operations.

The key here is to use the encoder specified in the message properties which may be MTOM for this kind of streamed message but it might be different according to the configured binding. After writing all the message content to memory, we may read from memory and create a string so we can easily inspect the actual message. If we know that we will always deal with XML content, we can use an XmlReader or the like to manipulate the content without the string conversion which may pay a performance penalty on large messages.

In the above code, we return the content as string because we may get an XML or Text formatted message so we can process accordingly.

In the next post I will show how we can use this code for inspecting a message to perform a custom authorization with ServiceAuthorizationManager.

Stay tuned!

1 Comment

  • My brother recommended I might like this website. He
    was totally right. This post actually made my day.
    You cann't imagine just how much time I had spent for this information! Thanks!

Comments have been disabled for this content.