Sending JSON in .NET Core
By FoxLearn 1/10/2025 8:31:40 AM 45
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:
- Serialization: You serialize the object using
JsonConvert.SerializeObject(someObject)
. - Base64 Encoding: The resulting JSON string is then Base64 encoded using the
Base64Encode
method. - 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.
- How to Convert string to JSON in C#
- How to take a screenshot with Selenium WebDriver
- Writing Files Asynchronously with Multiple Threads in .NET Core
- Manipulating XML Google Merchant Data with C# and LINQ
- Set Local Folder for .NET Core in C#
- How to Remove Duplicates from a List with LINQ in C#
- HttpClient Follow 302 Redirects in .NET Core
- Ignoring Namespaces in XML when Deserializing in C#