Raymond Raymond / Code Snippets & Tips

C#: Base64 URL Encoder and Decoder

event 2021-08-24 visibility 2,906 comment 0 insights toc
insights Stats

Base64 is commonly used to encode binary data. When using it in web application URLs, it is important to encode and decode it properly as there are three special characters used in the encoding: +, / and =. These three characters can be parsed differently in URLs.

Encode and decode code snippet

The following code snippet encode and then decode a string using utility class Microsoft.IdentityModel.Tokens.Base64UrlEncoder:

using Microsoft.IdentityModel.Tokens;

var originalText = "I am the original text.";
var encoded = Base64UrlEncoder.Encode(originalText);
var decoded = Base64UrlEncoder.Decode(encoded);

The encode function performs base64url encoding which differs from regular base64 encoding as follows

  • padding is skipped so the pad character '=' doesn't have to be percent encoded
  • the 62nd and 63rd regular base64 encoding characters ('+' and '/') are replace with ('-' and '_')

These changes make the encoding alphabet file and URL safe.


dotnet run
I am the original text.

Add the package

Run the following command to add the package:

dotnet add package Microsoft.IdentityModel.Tokens


Base64UrlEncoder Class (Microsoft.IdentityModel.Tokens) - Azure for .NET Developers | Microsoft Docs

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts