6

I have a simple Azure WebJobs ServiceBusTrigger that looks like

public static async void ProcessQueueMessage([ServiceBusTrigger("myqueuename")] String json, TextWriter log) { ... }

Unfortunately, it is failing to deserialize JSON as XML (not surprising). I have inspected the payload and confirmed that it is just a UTF-8 encoded array of bytes. I have two questions.

  1. Why is it assuming that my String is XML?
  2. How do I tell it no, there is no XML, there is just a string?

Stack trace:

System.InvalidOperationException: Exception binding parameter 'json' ---> System.Runtime.Serialization.SerializationException: There was an error deserializing the object of type System.String. The input source is not correctly formatted. ---> System.Xml.XmlException: The input source is not correctly formatted.
 at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
 at System.Xml.XmlBufferReader.ReadValue(XmlBinaryNodeType nodeType, ValueHandle value)
 at System.Xml.XmlBinaryReader.ReadNode()
 at System.Xml.XmlBinaryReader.Read()
 at System.Xml.XmlBaseReader.IsStartElement()
 at System.Xml.XmlBaseReader.IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
 at System.Runtime.Serialization.XmlReaderDelegator.IsStartElement(XmlDictionaryString localname, XmlDictionaryString ns)
 at System.Runtime.Serialization.XmlObjectSerializer.IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns)
 at System.Runtime.Serialization.DataContractSerializer.InternalIsStartObject(XmlReaderDelegator reader)
 at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
 at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
 --- End of inner exception stack trace ---
 at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
 at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)
 at Microsoft.ServiceBus.Messaging.DataContractBinarySerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)
 at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(XmlReader reader, Boolean verifyObjectName)
 at System.Runtime.Serialization.XmlObjectSerializer.InternalReadObject(XmlReaderDelegator reader, Boolean verifyObjectName)
 at System.Runtime.Serialization.XmlObjectSerializer.InternalReadObject(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
 at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
 at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(XmlDictionaryReader reader)
 at Microsoft.ServiceBus.Messaging.DataContractBinarySerializer.ReadObject(Stream stream)
 at Microsoft.ServiceBus.Messaging.BrokeredMessage.GetBody[T](XmlObjectSerializer serializer)
 at Microsoft.ServiceBus.Messaging.BrokeredMessage.GetBody[T]()
 at Microsoft.Azure.WebJobs.ServiceBus.Triggers.BrokeredMessageToStringConverter.ConvertAsync(BrokeredMessage input, CancellationToken cancellationToken)
 at Microsoft.Azure.WebJobs.ServiceBus.Triggers.ConverterArgumentBindingProvider`1.ConverterArgumentBinding.<BindAsync>d__0.MoveNext()

Edit: The WebJobs documentation suggests that not only should what I did work (String) but ServiceBusTrigger should automatically deserialize JSON objects. However, if I try to get my POCO out I still get an XML deserialization error. Interestingly, I also get an XML deserialization error if I set the type as Byte[], which is also supposed to work.

Edit 2: Stream also does not work. It appears that only BrokeredMessage works for the trigger, and GetBody is the only way I can find to get the String out of the BrokeredMessage.

1
  • 2
    I had this exact problem but through trying @mahesh-kshirsagar's CustomMessageProvider solution below found that the ContentType of the message was "json" when it should be "application/json"; this hadn't been an issue with worker role ServiceBus handlers but the "automagic" WebJob deserialization falls back to "application/xml". Fortunately I was able to fix the ContentType where the message was raised.
    – PeteB
    Jun 22, 2016 at 16:06

4 Answers 4

3

I was able to get deserialization work by adding a custom message processor.

Custom message processor example is available at https://github.com/Azure/azure-webjobs-sdk-samples/tree/master/BasicSamples/MiscOperations

You set the ContentType to application/json as below -

public class CustomMessagingProvider : MessagingProvider
{
    private readonly ServiceBusConfiguration _config;

    public CustomMessagingProvider(ServiceBusConfiguration config) : base(config)
    {
        _config = config;
    }

    public override MessageProcessor CreateMessageProcessor(string entityPath)
    {
        return new CustomMessageProcessor(_config.MessageOptions);
    }

    private class CustomMessageProcessor : MessageProcessor
    {
        public CustomMessageProcessor(OnMessageOptions messageOptions)
            : base(messageOptions)
        {
        }

        public override Task<bool> BeginProcessingMessageAsync(BrokeredMessage message, CancellationToken cancellationToken)
        {
            message.ContentType = "application/json";

            return base.BeginProcessingMessageAsync(message, cancellationToken);
        }
    }
}

You then set this message processor when configuring ServiceBusConfiguration in webjob.

 JobHostConfiguration config = new JobHostConfiguration();
        ServiceBusConfiguration serviceBusConfig = new ServiceBusConfiguration
        {
            ConnectionString = _servicesBusConnectionString
        };

        serviceBusConfig.MessagingProvider = new CustomMessagingProvider(serviceBusConfig);

        config.UseServiceBus(serviceBusConfig);
2

If your payload is String the you have two options:

  1. Change the parameter type to BrokeredMessage and then deserialize it yourself
  2. Set the BrokeredMessage.ContentType property to text/plain (this assumes that you have control over the code that generates the message)

Except for the weird String case in which you need the content type, the rule is that service bus payloads can be deserialzed only to the same object as the payload. That's because of the ServiceBus binary serializer.

7
  • I didn't know there was a content type, thanks! I'll fiddle with it when I get home, but do you know if I set it to the correct thing (application/json in this case) can I still pull out a String and manually deserialize? Jan 6, 2015 at 16:04
  • No, unfortunately it doesn't deserialize JSON POCO like it does for Azure Storage Queues so setting the content type to application/json will not do anything Jan 6, 2015 at 21:43
  • Even if it doesn't deserialize it automatically, if I set it to application/json will I at least be able to pull a String out without it trying to deserialize it as XML? I can parse it on my own easily enough, I would just like to be able set the content type to what it actually is rather than having to claim the message is text/plain even though it isn't. Jan 6, 2015 at 23:42
  • This answer "solves" my problem, (setting the content type on the message to text/plain) but it still doesn't answer why the ServiceBusTrigger is trying to deserialize anything other than application/xml with an XML deserializer. I did try setting the content type to application/json, and it still tried to use the XML deserializer. Jan 7, 2015 at 3:36
  • Actually, it appears that this is a ServiceBus issue, not an Azure WebJobs issue. I'll put together a simpler repro case and file a bug (however one does that for Service Bus). Jan 7, 2015 at 3:37
2

In answer to #2, a hacky workaround is to get a BrokeredMessage from the ServiceBusTrigger and call message.ToBody<Stream>(). Then you can use do the normal stuff for turning a stream of bytes into a String.

Example of getting a JSON encoded payload deserialized into an object:


public static async void ProcessQueueMessage([ServiceBusTrigger("my-queue")] BrokeredMessage message)
{
    var stream = message.ToBody();
    using (var streamReader = new StreamReader(stream, Encoding.UTF8)
    {
        var json = await streamReader.ReadToEndAsync();
        var deserialized = JsonConvert.DeserializeObject(json);
    }
}

Note: I am still interested in a better answer if someone has one. In a perfect world, I would be able to supply the ServiceBusTrigger with a custom deserializer (JSON.net based or just a String deserializer), but I don't know how to do this if it is possible.

1
  • Check out my answer. I think it may be closer to what you were looking for.
    – ElvisLives
    Jun 13, 2016 at 20:52
2

I found some voodoo when I was researching this issue.

We were doing fine with the binary serialization but wanted to see what the body of the message is when we are watching webjobs process the events via the webjobs dashboard. I stole code from WebJobs ServiceBus code on github to solve this issue. I am still a little confused on why you have to serialize the poco into JSON and pack it in a memory stream and then set the content type to application/json. My conclusion is there must be something internally with the Azure Service Bus SDK that expects it. I didn't find that code yet but in testing it works great.

First we had this case where the object being serialized in the webjobs dashboard is just bytes.

eventDto is shown as bytes

After using the code below to put messages on the bus we end up with:

eventDto has json value

We didn't have to change the signature on the consuming side and now we can see the body of our BrokeredMessage. public void PersistEvents([ServiceBusTrigger(EventProcessor.CoolTopicName, LoggingSubscription)] EventDto eventDto, TextWriter logger)

Here is the code for the Azure ServiceBus SDK that fixed it.
And here is my example Code (Borrowed from the SDK): string json = JsonConvert.SerializeObject(eventDto); // Using Json.net here MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json), writable: false); BrokeredMessage message = new BrokeredMessage(stream); message.ContentType = "application/json"; client.Send(message);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.