0
    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 ?

Neo
  • 15,491
  • 59
  • 215
  • 405

1 Answers1

2

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);
Mikhail Shilkov
  • 34,128
  • 3
  • 68
  • 107
  • oh great exaplanation thanks a lot :) which is good to use stream or string ? – Neo Sep 03 '18 at 08:35
  • 1
    Both are okay, but you have to keep sender and receiver in sync. If you already serialize to JSON, then `Stream` makes more sense to me. – Mikhail Shilkov Sep 03 '18 at 08:37
  • i'm reading message using Microsoft.ServiceBus.Messaging.MessageReceiver messageReceiver – Neo Sep 03 '18 at 08:39