Search code examples
c#azureservicebusazure-webjobsazure-servicebus-queuesazure-servicebus-topics

Receiving a message using Azure.Messaging.ServiceBus that was sent with Microsoft.ServiceBus.Messaging (ServiceBus.v1_1)


We send servicebus messages with an old library via Microsoft.ServiceBus.Messaging which is available in the nuget-package 'ServiceBus.v1_1' and want to receive and parse the message with the newest service bus client: Azure.Messaging.ServiceBus.

[FunctionName("FunctionHandler")]
public async Task RunFunction(
    [ServiceBusTrigger("%ServiceBusQueueName%", Connection = ApFunctionDefaults.ServiceBusNames.ServiceBusConnectionString)]
    ServiceBusReceivedMessage queueMessage)
{
    var jsonSettings = KnownTypesBinder.GetSerializerSettings(KnownTypeProvider.GetKnownTypes());
    command = JsonConvert.DeserializeObject<MyDto>(Encoding.UTF8.GetString(queueMessage.Body), jsonSettings); // <- throws an exception
}

The body of the message queueMessage.Body has some value like that:

@\u000eCommandMessage\bUhttp://schemas.datacontract.org/2004/07/ ...more payload here... a\u0001"

With JsonConvert.DeserializeObject, we get an format exception.

How do we deserialize a message which was send by Microsoft.ServiceBus.Messaging (Nuget-Package: ServiceBus.v1_1) with Azure.Messaging.ServiceBus?


Solution

  • The legacy package uses a DataContractSerializer to encode the paylaod, where newer generations treat the message payload as an opaque blob of bytes. To process the message using Azure.Messaging.ServiceBus, you'll need to decode the body.

    // receive the message
    var receiver = client.CreateReceiver(queueName);
    var receivedMessage = await receiver.ReceiveMessageAsync();
    
    // deserialize the XML envelope into a string
    var deserializer = new DataContractSerializer(typeof(MyDto));
    
    var reader = XmlDictionaryReader.CreateBinaryReader(
        receivedMessage.Body.ToStream(), 
        XmlDictionaryReaderQuotas.Max);
    
    MyDto myDto = deserializer.ReadObject(reader);
    
    

    More context and discussion can be found in the Service Bus interop sample.