DEV Community

Cover image for Mastering URL‑Safe Encoding with .NET 9’s Base64Url Class: Examples & Best Practices
Leandro Veiga
Leandro Veiga

Posted on

5

Mastering URL‑Safe Encoding with .NET 9’s Base64Url Class: Examples & Best Practices

With .NET 9 Microsoft has introduced a dedicated Base64Url class to streamline URL‑safe Base64 encoding and decoding. In this post, you’ll learn:

  • Why URL‑safe Base64 matters
  • How to use the new Base64Url API in .NET 9
  • Real‑world use cases (tokens, query strings, data embedding)
  • Best practices to avoid common pitfalls

Let’s dive in!

Table of Contents

Introduction

Base64 is a popular encoding mechanism for binary-to-text transformations. However, standard Base64 uses characters like +, /, and = which can break URLs or require extra escaping. URL‑safe Base64 replaces these with -, _, and omits padding, making it ideal for tokens, query parameters, and other web contexts.

.NET 9’s new Base64Url class provides:

  • Simple, zero‑allocation methods
  • Consistent behavior across platforms
  • Built‑in handling of padding and illegal characters

Why URL‑Safe Base64?

Standard Base64:

  • Uses + and / in its alphabet
  • Adds = padding at the end
  • Requires URL‑encoding when used in query strings
  • Can introduce parsing errors or double‑encoding

URL‑safe Base64:

  • Substitutes +- and /_
  • Omits or gracefully handles padding
  • Safe to embed in URLs without extra encoding

The .NET 9 Base64Url Class

The new class lives in the System namespace:

namespace System
{
    public static class Base64Url
    {
        public static string Encode(byte[] data);
        public static byte[] Decode(string urlSafeBase64);
    }
}
Enter fullscreen mode Exit fullscreen mode

Key points:

  • Encode(byte[]) produces a URL‑safe string (no +, /, or trailing =).
  • Decode(string) accepts padded or unpadded URL‑safe Base64 strings.

Code Examples

Encoding & Decoding Strings

using System;
using System.Text;

class Program
{
    static void Main()
    {
        string original = "Hello, .NET 9!";
        byte[] bytes = Encoding.UTF8.GetBytes(original);

        // Encode to URL-safe Base64
        string encoded = Base64Url.Encode(bytes);
        Console.WriteLine($"Encoded: {encoded}");
        // e.g. "SGVsbG8sIC5ORGVDOSA"

        // Decode back to bytes
        byte[] decodedBytes = Base64Url.Decode(encoded);
        string decoded = Encoding.UTF8.GetString(decodedBytes);

        Console.WriteLine($"Decoded: {decoded}");
        // "Hello, .NET 9!"
    }
}
Enter fullscreen mode Exit fullscreen mode

Working with Binary Data

using System;
using System.Security.Cryptography;

class BinaryExample
{
    static void Main()
    {
        // Generate a random 32-byte key
        byte[] key = RandomNumberGenerator.GetBytes(32);

        // URL-safe encode the key
        string keyToken = Base64Url.Encode(key);
        Console.WriteLine($"Key Token: {keyToken}");

        // Later: decode back to raw key
        byte[] rawKey = Base64Url.Decode(keyToken);
        Console.WriteLine($"Key Length: {rawKey.Length} bytes");
    }
}
Enter fullscreen mode Exit fullscreen mode

Integrating with ASP.NET Core

Embed URL‑safe tokens in query strings or headers:

app.MapGet("/token", () =>
{
    var payload = Encoding.UTF8.GetBytes("user-id=42;exp=1699999999");
    var token = Base64Url.Encode(payload);
    return Results.Ok(new { token });
});

app.MapGet("/validate", (string token) =>
{
    try
    {
        var data = Base64Url.Decode(token);
        string text = Encoding.UTF8.GetString(data);
        return Results.Ok(new { valid = true, text });
    }
    catch (FormatException)
    {
        return Results.BadRequest("Invalid token format.");
    }
});
Enter fullscreen mode Exit fullscreen mode

Common Use Cases

  • JWT & OIDC – JSON Web Tokens use URL‑safe Base64 for header and payload segments.
  • Query Parameters – Pass binary data or state tokens without further URL encoding.
  • Short-Lived URLs – Sign URLs for temporary access (e.g., presigned file downloads).
  • Embedded Metadata – Include user data in links or forms safely.

Best Practices

  • Validate Input: Always wrap Decode in try/catch to handle malformed input.
  • Avoid Manual Padding: Let Base64Url handle padding rules automatically.
  • Use in HTTPS: Although URL‑safe, still transmit sensitive tokens over secure channels.
  • Log & Monitor: Track decode failures to detect tampering or abuse.
  • Cache Heavy Operations: If encoding large blobs frequently, consider caching results.

Conclusion

.NET 9’s Base64Url class simplifies URL‑safe encoding and decoding with a clean, reliable API. Whether you’re building authentication tokens, passing data in query strings, or signing URLs, Base64Url should be your go‑to tool.

Give it a try in your next .NET 9 project, and let me know how you use it!

Happy coding!

Sentry blog image

Build, Ship, See It All: MCP Monitoring with Sentry

Built an MCP server? Now see everything it does. Sentry’s MCP Server Monitoring tracks every client, tool, and request so you can fix issues fast and build with confidence.

Read more

Top comments (0)

Premium Residential Proxies,Unlock the Ultimate Web Scraping

Premium Residential Proxies,Unlock the Ultimate Web Scraping

Tired of getting blocked while scraping? Say hello to seamless, scalable, and stealthy web scraping with our top-tier residential proxy network.
🔥60M+ ethically sourced Residential IPs
💸Pricing starts from $1.80/GB
⚡Extremely stable proxies with 99.7% uptime

🚀 Try Risk-Free – No Credit Card

👋 Kindness is contagious

Explore this insightful write-up, celebrated by our thriving DEV Community. Developers everywhere are invited to contribute and elevate our shared expertise.

A simple "thank you" can brighten someone’s day—leave your appreciation in the comments!

On DEV, knowledge-sharing fuels our progress and strengthens our community ties. Found this useful? A quick thank you to the author makes all the difference.

Okay