Search code examples
xmlserializationnamespacesazureservicebusbrokeredmessage

Unknown xml serialization content/namespace from Service bus brokered message


Hi i was wondering why i get a special namespace in my brokered message content from my service bus when i fetch the message from the topic. and how do i remove it?

i have my xml, and when i (in my Azure function) try to retrieve the message from the service bus i get this on top of everything or better said before my root node:

@string3http://schemas.microsoft.com/2003/10/Serialization/��
    <rootNode>...</rootNode>

when i retrieve the brokered message from my servicebus in my azure function i do it like this:

string BrokeredMessageBody = mySbMsg.GetBody<string>();

FYI: in the Azure Function the xml looks alright, but when my logic app gets it it somehow adds the above namespace as specified earlier/above.

Anyone encountered this before?


Solution

  • My guess would be that this is how you send your messages:

    string content = "My message";
    var message = new BrokeredMessage(content);
    

    However, this does not send your content as-is. You are actually using this constructor overload:

    public BrokeredMessage(object serializableObject)
    

    and it does:

    Initializes a new instance of the BrokeredMessage class from a given object by using DataContractSerializer with a binary XmlDictionaryWriter.

    So, your string gets serialized into XML and then formatted with binary formatting. That's what you see in the message content (namespace and some non-readable characters).

    Your Azure Function works fine, because mySbMsg.GetBody<string>(); does the reverse - it deserializes the message from binary XML.

    To serialize the content as-is, you should be using Stream-based constructor overload:

    string content = "My message";
    var message = new BrokeredMessage(new MemoryStream(Encoding.UTF8.GetBytes(content)), true);
    

    Note that you define the string encoding yourself (UTF-8 in my example).

    Reading gets a bit more involved too:

    using (var stream = message.GetBody<Stream>())
    using (var streamReader = new StreamReader(stream, Encoding.UTF8))
    {
        content = streamReader.ReadToEnd();
    }