Search code examples
serializationazure-storagemessageazureservicebusbrokeredmessage

Azure service bus Message deserialize broken in core conversion


So, I've created a new Azure Functions project v3 and am porting over a subset of functions from v1 that was running on 4.6.2, while retiring the rest as obsolete. Unfortunately in the change from BrokeredMessage to Message due to changing from Microsoft.ServiceBus.Messaging to Microsoft.Azure.ServiceBus the following deserialization method is now failing with:

There was an error deserializing the object of type stream. The input source is not correctly formatted.

The problem is right there in the error, but Im not sure what the correct new approach is, its a bit unclear.

Serialize

public static Message CreateBrokeredMessage(object messageObject)
{

       var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageObject)))
       {
           ContentType = "application/json",
           Label = messageObject.GetType().Name

       };

       return message;
}

Deserialize

public static T ParseBrokeredMessage<T>(Message msg)
{
     var body = msg.GetBody<Stream>();
     var jsonContent = new StreamReader(body, true).ReadToEnd();
     T updateMessage = JsonConvert.DeserializeObject<T>(jsonContent);

     return updateMessage;
}

Object

                   var fileuploadmessage = new PlanFileUploadMessage()
                    {
                        PlanId = file.Plan_Id.Value,
                        UploadedAt = uploadTimeStamp,
                        UploadedBy = uploadUser,
                        FileHash = uploadedFileName,
                        FileName = file.Name,
                        BusinessUnitName = businessUnitName,
                        UploadedFileId = uploadedFile.Id
                    };
    ```

Solution

  • Message.GetBody<T>() is an extension method for messages sent using the legacy Service Bus SDK (WindowsAzure.ServiceBus package) where BrokeredMessage was populated with anything other than Stream. If your sender sends an array of bytes as you've showed, you should access it using Message.Body property.

    In case your message is sent as a BrokeredMessage, the receiving code will need to select either of the methods based on some information to indicate how the message was originally sent.