When processing URL -based applications, the base64 encoding is critical to ensure data integrity and readability. In C#, the built -in Base64 encoding function provides a convenient way to convert binary data into text -based forms. However, it adds the characters ("==") to the coding string, which may cause problems when used in URL.
URL security encoding
In order to overcome this limit, the URL security encoding is deleted and filled characters, and the specific problem characters ("", "/", "=") are replaced with URL-friendly characters ("-", "_", "") Essence This ensures that the coding string can be transmitted to the URL parameter safely without causing any interpretation problems.
Unlike the CODEC library of Java, C#has no built -in URL security encoding function. However, you can achieve the same results through a few simple steps:
Use Execute the conventional base64 encoding.
Convert.ToBase64String()
Use to replace the problem character (for example, replace "" "- "and"/"to" _ "). TrimEnd()
Example Replace()
Inverse process
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes("StringToEncode"); string returnValue = System.Convert.ToBase64String(toEncodeAsBytes) .TrimEnd(new char[] {'='}).Replace('+', '-').Replace('/', '_');
Replace URL -friendly characters with its original corresponding characters.
Fill the character string to multiple times with the '=' character if necessary. Use to convert the string back to binary data.
Example
The above is the detailed content of How to Achieve URL-Safe Base64 Encoding and Decoding in C#?. For more information, please follow other related articles on the PHP Chinese website!