Sending JSON in .NET Core

By FoxLearn 1/10/2025 8:31:40 AM   45
In .NET Core, the Microsoft.Azure.Storage.Queue package has been replaced with the Azure.Storage.Queues package, and the CloudQueueMessage you used to send messages via queue.AddMessageAsync() has been simplified into the SendMessageAsync(string) method.

If you try to add a serialized JSON object to the queue directly, you might encounter an error when attempting to open the queue in Visual Studio.

The error message you'll get is:

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.

The error occurs because the SendMessageAsync method expects the message to be Base64 encoded, but sending a serialized JSON string does not fulfill this requirement.

Solution: Base64 Encoding the Serialized JSON

To resolve this, you need to Base64 encode the serialized JSON string before sending 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 Convert.ToBase64String(plainTextBytes);
}

In this example:

  1. Serialization: You serialize the object using JsonConvert.SerializeObject(someObject).
  2. Base64 Encoding: The resulting JSON string is then Base64 encoded using the Base64Encode method.
  3. Sending the Message: The encoded string is passed to SendMessageAsync, which successfully queues it.

When reading the message from the queue, you do not need to Base64 decode the string. The Azure Queue SDK handles decoding for you, and the serialized JSON will be directly readable.

While the change to SendMessageAsync simplifies the API, Base64 encoding is required when sending serialized objects to ensure compatibility with the Azure Queue service.