Search code examples
c#azureazure-functionsazure-storage-queues

How to bind queue-triggered Azure Function to a custom object


While writing a queue-triggered Azure Function I read that, by default, it expects a base-64 encoded string, but that it can also bind to a POCO.

Access the message data by using a method parameter such as string paramName. The paramName is the value specified in the QueueTriggerAttribute. You can bind to any of the following types:

  • Plain-old CLR object (POCO)
  • string byte[]
  • QueueMessage

When binding to an object, the Functions runtime tries to deserialize the JSON payload into an instance of an arbitrary class defined in your code.

[documentation]

When I try this, the exception is...

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

Tantalisingly, I've read that I should reference Microsoft.Azure.WebJobs.Extensions.Storage.Queues, but I can't find any examples or documentation on how to use this.

I referenced the NuGet package and Visual Studio now underlines the QueueTriggerAttribute as ambiguous due to being in two namespaces; When I try to fully-qualify it, I can't find it.

In several places I've found bloggers alluding to using ...Extensions.Storage... to bind a custom object but I've been searching for over an hour and I can't find any example or clear documentation on how to achieve this.

Am I missing something simple?


Solution

  • While writing a queue-triggered Azure Function I read that, by default, it expects a base-64 encoded string, but that it can also bind to a POCO.

    Correct, but in order to bind to a POCO the message still must be a base64 encoding string containing valid JSON that can be used to deserialize into an instance of the POCO class.

    You can try it using for example the Storage Explorer:

    enter image description here

    using Microsoft.Azure.WebJobs;
    using Microsoft.Extensions.Logging;
    
    namespace FunctionApp3
    {
        public class Function
        {
            [FunctionName("Function")]
            public void Run([QueueTrigger("queue", Connection = "MyConn")] MyObject myQueueItem, ILogger log)
            {
                log.LogInformation($"C# Queue trigger function processed: {myQueueItem.Name}");
            }
        }
    
        public class MyObject
        {
            public string Name { get; set; }
        }
    }