BrokeredMessage send and Message consumer in Azure

2019-07-27 00:08发布

问题:

I have mock azure web jobs, which periodically push BrokeredMessage to the service bus topic, like this

public void Simulate(
            [TimerTrigger("0 */30 * * * *", RunOnStartup = true)]
            TimerInfo timerInfo,
            [ServiceBus("%topic%")]
            out BrokeredMessage message)
        {
            message = new BrokeredMessage(
                new AwesomeContract()
                {

                });
        }

In azure function V2, I am trying to consume it using Message class.

public static void Integrate(
            [ServiceBusTrigger(
                "%topic%",
                "%subscribtion%",
                Connection = "ServiceBusConnection")] Message message,
            TraceWriter log,
            ExecutionContext context)
        {
            try
            {
              message.GetBody<AwesomeContract>();
            }
        }

On GetBody<> I receive DataContractSerialization exception "There was an error deserializing the object of type . The input source is not correctly formatted."

Are BrokeredMessage and Message compatible in azure function v1 and v2? Any suggestions?

回答1:

BrokeredMessage is the message object from the library WindowsAzure.ServiceBus, where Message is the object from the library Microsoft.Azure.ServiceBus.

Even though the object type differs between these libraries, sending the message body as a Stream will help in overcoming the exception while reading the body.

message = new BrokeredMessage(new MemoryStream(Encoding.UTF8.GetBytes([message_body]));

Constructing the message as above will help.



回答2:

I stumbled upon the following interop class while attempting to find help for a similar issue: Microsoft.Azure.ServiceBus.Extensions.MessageInterOpExtensions.cs note: the examples in the documentation all assumes that you have access to the messagereceiver, which being in an Azure Function you most likely do not.

According to the comment there, your particular configuration should work, but apparently there is some unknown error there - you may have to roll your own extension, or see if you can use the message.Body byte[] property

The BrokeredMessage constructor for custom objects says that it is using DataContractSerializer with a binary XmlDictionaryWriter, so if we know what the Content-Type is, we may be able to see why the DataContractSerializer fails.

If all else fails, or untill this apparent bug is fixed, you may have to see if you can use the byte array in the Body property and roll your own serializer/extension method.