Search code examples
c#azurestreamazureservicebusbrokeredmessage

I'm getting extra string char when I use GetBody<System.IO.Stream>() for BrokeredMessage but works perfect with GetBody<string>() c#


    Microsoft.ServiceBus.Messaging.MessageReceiver messageReceiver = messagingFactory.CreateMessageReceiver(                    Microsoft.ServiceBus.Messaging.SubscriptionClient.FormatSubscriptionPath(
                        "TopicName",
                        "SubscriptionName"),
                    Microsoft.ServiceBus.Messaging.ReceiveMode.PeekLock);

 List<BrokeredMessage> brokeredMessages = new List<BrokeredMessage>();
 var messages = messageReceiver.ReceiveBatch(10);
 brokeredMessages.AddRange(messages);

 foreach (var message in messages)              
 var stream = message.GetBody<System.IO.Stream>();
                    var reader = new StreamReader(stream);
                    var body = reader.ReadToEnd();

which gives wrong output with -

@string3http://schemas.microsoft.com/2003/10/Serialization/�h
{"MyID":"121"}

When I use below it works perfect -

string body = message.GetBody<string>();

output - {"MyID":"121"}

why this happens ?


Solution

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

    MyClass myObj = new MyClass { MyID = "121" };
    string json = ... // serialize myObj to JSON
    var message = new BrokeredMessage(json);
    

    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).

    message.GetBody<string> works fine, because it does the reverse: it deserializes the message from binary XML.

    message.GetBody<Stream> is a raw operation, thus you get raw bytes.

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

    var message = new BrokeredMessage(new MemoryStream(Encoding.UTF8.GetBytes(json)), true);