Search code examples
azureasp.net-core.net-coreazureservicebusservicebus

Azure service bus - Read messages sent by .NET Core 2 with BrokeredMessage.GetBody


I am using .NET Core 2 for an application which needs to put a message on the Service bus and read by a legacy .NET 4.6 receiver. The receiver listens to messages from other legacy applications as well.

Legacy sender:

UserData obj = new UserData()
{
  id = 1,
  name = "Alisha"
};
BrokeredMessage message = new BrokeredMessage(consentInstated);
_client.Send(message);

Legacy Receiver:

var dataObj = objBrokeredMessage.GetBody<UserData>();
businessFunc(dataObj.id, dataObj.name);

.NET Core 2 sender: as described in https://stackoverflow.com/a/45069423/1773900

var ser = new System.Runtime.Serialization.DataContractSerializer(typeof(UserData));
var ms = new MemoryStream();
ser.WriteObject(ms, objUserData);
var message = new Message(ms.ToArray());
_client.Send(message);

However, the reciever fails to deserialize the message and throws the following error

System.Runtime.Serialization.SerializationException: There was an error deserializing the object of type UserData. The input source is not correctly formatted. ---> System.Xml.XmlException: The input source is not correctly formatted.

What can I do to make both senders work with the same receiver?


Solution

  • BrokeredMessage is using XML Binary Reader to deserialize the messages. So your sending part should look like this:

    var ser = new DataContractSerializer(typeof(UserData));
    var ms = new MemoryStream();
    XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(ms);
    ser.WriteObject(binaryDictionaryWriter, obj);
    binaryDictionaryWriter.Flush();
    var message = new Message(ms.ToArray());