关于c#:Convert.ToBase64String(byte [])和HttpServerUtility.UrlTokenEncode(byte [])之间有什么区别?

What is the difference between Convert.ToBase64String(byte[]) and HttpServerUtility.UrlTokenEncode(byte[])?

我正在尝试从Web API项目中删除对System.Web.dll的依赖,但是偶然发现了对我不知道要替换以确保向后兼容性的HttpServerUtility.UrlTokenEncode(byte[] input)(及其对应的解码方法)的调用。 文档说这种方法

Encodes a byte array into its equivalent string representation using base 64 digits, which is usable for transmission on the URL.

我尝试用Convert.ToBase64String(byte[] input)(及其对应的解码方法)代替,这在文档中有非常相似的描述:

Converts an array of 8-bit unsigned integers to its equivalent string representation that is encoded with base-64 digits.

但是,它们似乎并不完全相同。 当使用Convert.FromBase64String(string input)解码用HttpServerUtility编码的字符串时,出现异常说明

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

这两个转换实用程序有什么区别? 消除对System.Web.HttpServerUtility的依赖性的正确方法是什么?

一些用户建议这是此副本的副本,但我不同意。 这个问题是关于通常以url安全的方式对字符串进行base-64编码的,但是我需要重现HttpServerUtility的确切行为,但不依赖于System.Web


我以DGibbs的话为准,并使用了Source。事实证明,在HttpServerUtility方法中发生以下情况:

编码为Base64

  • 使用System.Convert将输入转换为Base64。

  • +替换为-,将/替换为_。示例:Foo+bar/===变为Foo-bar_===

  • 替换字符串末尾的任意数量的=,并用整数表示它们的数量。示例:Foo-bar_===变为Foo-bar_3

  • 从Base64解码

  • 用相同数量的=符号替换字符串末尾的数字。示例:Foo-bar_3变为Foo-bar_===

  • -替换为+,将_替换为/。示例:Foo-bar_===变为Foo+bar/===

  • 使用System.Convert解码来自Base64的预处理输入。


  • HttpServerUtility.UrlTokenEncode(byte[] input)将对URL安全的Base64字符串进行编码。在Base64 +中,/和=字符有效,但它们不是URL安全的,此方法将替换这些字符,而Convert.ToBase64String(byte[] input)则无效。您可能会删除参考,自己动手做。

    通常,将'+'替换为'-',将'/'替换为'_',仅删除'='。

    这里接受的答案给出了一个代码示例:如何在C#中实现Base64 URL安全编码?