URL Safe Base64 Encoding/Decoding in ASP.NET Framework
Base64 encoding is commonly used to encode binary data into a text format for transmission over a network. However, the standard Base64 encoding contains characters (especially " " and "/") that may interfere with URI templates and URLs.
To solve this problem, a modified version of Base64 encoding exists specifically for URLs. In this variant, " " and "/" are replaced by "-" and "_" respectively, and the padding character "=" is omitted.
Implementing a modified version of Base64 for URLs in the ASP.NET framework can use the following method:
Decoding:
Encoding:
Alternative:
.NET Framework provides the HttpServerUtility class, which contains the UrlTokenEncode and UrlTokenDecode methods that handle URL-safe Base64 encoding and decoding.
Code:
<code class="language-csharp">// 编码 string base64UrlEncodedText = HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(plaintext)); // 解码 string plaintext = Encoding.UTF8.GetString(HttpServerUtility.UrlTokenDecode(base64UrlEncodedText));</code>
Note: HttpServerUtility method returns a non-standard base64url implementation in which the "=" padding character is replaced with "0", "1" or "2". This is different from the RFC4648 standard, which uses the "=" character for padding.
The above is the detailed content of How to Perform URL-Safe Base64 Encoding and Decoding in ASP.NET?. For more information, please follow other related articles on the PHP Chinese website!