Skip to main content
.NET Tips

URL-Safe Base64 Encoding With .NET 9

.NET 9 introduces a new Base64Url type for URL-safe Base64 encoding, solving the issue of unsafe characters like /, +, and =.

Christian Schou Køster

In .NET 9 we will get a new Base64Url Type. It will make it possible for developers to do URL-safe Base64 encoding on the fly.

Coming from earlier version of .NET you might think, why? We already have the Convert.ToBase64String() method? That's correct, but that method can produce strings which contains characters such as: /, +,or =. These characters are not safe for use in URL's without encoding them first, because they are used for special operations.

To fix that, the .NET team now introduces a new Base64Url.EncodeToString() method. 👌

What Is Base64 And Why? 🤔

💡
Base64 is an encoding scheme that translates arbitrary bytes into text composed of a specific set of 64 characters. It's a common approach for transferring data and has long been supported via a variety of methods.

How To Use It 🧑‍💻

Here us a practical example of how to implement and use the Base64URL helper in .NET 9.

byte[] stringToEncode = Encoding.UTF8.GetBytes("Tech with Christian");

var unsafeEncoding = Convert.ToBase64String(stringToEncode);
var safeEncoding = Base64Url.EncodeToString(stringToEncode);

Console.WriteLine($"Unsafe encoding: {unsafeEncoding}");
Console.WriteLine($"Safe encoding: {safeEncoding}");

// Unsafe encoding: VGVjaCB3aXRoIENocmlzdGlhbg==
// Safe encoding: VGVjaCB3aXRoIENocmlzdGlhbg

That's how easy it is to use the new Base64Url class with the EncodeToString method. Just remember it's only available beginning from .NET 9.

Resources 📚

Base64Url Class (System.Buffers.Text)
Converts between binary data and URL-safe ASCII encoded text that’s represented in Base64Url characters.
What’s new in .NET libraries for .NET 9
Learn about the new .NET libraries features introduced in .NET 9.
Christian Schou Køster