带有ß字符的字符串的UrlEncoding问题

AFr*_*eze 0 c# encoding urlencode

我有一个参数,我必须作为网址的一部分传递.该参数包含以下字符:ß

当我编码这个字符串时,我期待这个:%DF,但我得到:%c3%9f

这是我用来测试的一系列C#

  string test = HttpUtility.UrlEncode("ß");
Run Code Online (Sandbox Code Playgroud)

csh*_*net 6

这是因为UrlEncode的默认实现基于UTF8字符编码.实际上,这完全在你的掌控之中.

例如,以下代码:

string sample = new string((char)0x0DF, 1);
string test = HttpUtility.UrlEncode(sample);
Console.WriteLine("UTF8 Ecoded: {0}", test);
test = HttpUtility.UrlEncode(sample, Encoding.GetEncoding(1252));
Console.WriteLine("1252 Ecoded: {0}", test);
Run Code Online (Sandbox Code Playgroud)

输出以下内容:

UTF8 Ecoded: %c3%9f
1252 Ecoded: %df
Run Code Online (Sandbox Code Playgroud)

当然,在URI上使用另一种编码的危险在于某些字符根本无法表示...

例如,这段代码:

string sample = new string((char) 312, 1);
Encoding encoding = Encoding.GetEncoding(1252);
string test = HttpUtility.UrlEncode(sample);
Console.WriteLine("UTF8 Ecoded: {0}, round-trip = {1}", test, sample == HttpUtility.UrlDecode(test));
test = HttpUtility.UrlEncode(sample, encoding);
Console.WriteLine("1252 Ecoded: {0}, round-trip = {1}", test, sample == HttpUtility.UrlDecode(test, encoding));
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

将输出以下内容:

UTF8 Ecoded: %c4%b8, round-trip = True
1252 Ecoded: %3f, round-trip = False
Run Code Online (Sandbox Code Playgroud)

您可以在后面的示例中看到编码是"%3f",当未编码时等于问号"?",而不是输入字符312(0x138).

简而言之,将"ß"编码为"%c3%9f"并没有错,相反,它是正确的表示.但是,如果您必须使用编码"%DF以便远程服务器正确解码它,那么请使用1252代码页,如图所示.