Sending JSON in .NET Core
By FoxLearn 1/10/2025 8:31:40 AM 129
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#