Search code examples
c#azure-functionsmessage-queueazure-queuesqueuetrigger

Azure Function QueueTrigger and int message


I want to save int value to queue message and then get it on Azure Function QueueTrigger.

I save by the following way:

        int deviceId = -1;
        await queue.AddMessageAsync(new CloudQueueMessage(deviceId.ToString()));

and then listen queue:

    public async Task Run(
        [QueueTrigger("verizon-suspend-device", Connection = "StorageConnectionString")] string queueMessage, 
        ILogger log)
    {
        int deviceId = int.Parse(queueMessage);

but all messages are being moved to verizon-suspend-device-poison queue. What is wrong?


Solution

  • It's an unfortunate limitation that Azure Function Queue Triggers currently require Base64-encoded messages. If you run your code against the storage emulator you should see an exception from your trigger like 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.

    For now, at least (i.e., until the trigger can handle binary/utf8 messages), queueing code has to place messages on the queues as Base64 strings. The queue trigger code for a string message ends up here, and AsString assumes a Base64 encoding.

    For that (old) version of the storage SDK, you can send a Base64-encoded UTF-8 string representation of the integer:

    var bytes = Encoding.UTF8.GetBytes(deviceId.ToString());
    await queue.AddMessageAsync(new CloudQueueMessage(Convert.ToBase64String(bytes), isBase64Encoded: true));
    

    With the new storage SDK, you would set MessageEncoding on your QueueClient to QueueMessageEncoding.Base64 and then just send the string representation of the integer (the new storage SDK will UTF-8 encode and then Base64-encode for you).