Reading a Binary XML stream in WCF

To cut the long story short, you can’t read a WCF binary XML stream without using the WCF binary XML dictionary. The WCF classes can read the binary format because they have the dictionary (which is defined internally, and is used to encode commonly used XML strings), but you don’t. So you need to create your own dictionary, defining the same keys, and then you will be able to read it – using the static CreateBinaryReader method of the XmlDictionaryReader class, and passing the dictionary to it.

Now for the long story. I was faced with this challenge when I needed to massage the SOAP message produced by a .NET web service built on WCF. If you don’t provide a dictionary to read the XML stream with, you will get a weird and unhelpful exception that says “the input source is not correctly formatted”, and googling around will only bring you to posts telling you that “your client/server endpoints are not matched” or “you need to use the basicHttpBinding”. This is not a binding issue –  it’s a deserialization issue that comes up when i make an attempt to inspect the soap messages coming in to (or going out of) my WCF service.

Actually, reading the incoming message gives no issues if I don’t use the WCF dictionary, since my XML elements aren’t in the dictionary and didn’t get encoded en-route anyway. However, reading the outgoing message gave issues because majority of the tags/strings in the output content were microsoft-known tags and had been encoded into their binary representation, but I didn’t have a dictionary to decode it.

The funny thing is, the ToString method of the message class (the SOAP message) gave me a fully human-readable XML representation of the outgoing soap message. I would have stopped my quest at this point, but I discovered that for very large messages the body part would appear as “… stream …”, which would be useless to me. So I continued searching until I found this stackoverflow question:

The complete WCF binary XML dictionary is defined here (note: it is a C# class with several lines of code).

Leave a comment