Sending JSON with .NET Core QueueClient.SendMessageAsync

In .NET Core, Microsoft.Azure.Storage.Queue have been replaced with Azure.Storage.Queues, and the CloudQueueMessage that you added using queue.AddMessageAsync() have been replaced with the simpler queue.SendMessageAsync(string) method.

But this introduces a strange situation, when adding serialized JSON objects. If you just add the serialized object to the queue:

using Azure.Storage.Queues;
using Newtonsoft.Json;
using System;

public async Task SendObject(object someObject)
{
  await queueClient.SendMessageAsync(JsonConvert.SerializeObject(someObject));
}

The queue cannot be opened from Visual Studio. You will get an error that the string is not Base 64 encoded.

System.Private.CoreLib: 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.

So you need to Base 64 encode the serialized object before adding it to the queue:

using Azure.Storage.Queues;
using Newtonsoft.Json;
using System;

public async Task SendObject(object someObject)
{
  await queueClient.SendMessageAsync(Base64Encode(JsonConvert.SerializeObject(someObject)));
}

private static string Base64Encode(string plainText)
{
  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  return System.Convert.ToBase64String(plainTextBytes);
}

When reading the serialized JSON string, you do not need to Base 64 decode the string, it will be directly readable.

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .NET Core, c#, General .NET, Microsoft Azure and tagged , , , . Bookmark the permalink.

1 Response to Sending JSON with .NET Core QueueClient.SendMessageAsync

  1. Pingback: Read from Azure Queue with .NET Core | Brian Pedersen's Sitecore and .NET Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.