我有一个必须作为 url 的一部分传递的参数。参数包含这个字符:ß
当我编码这个字符串时,我期待这个:%DF 但我得到的是:%c3%9f
这是我用来测试的一行 C#
string test = HttpUtility.UrlEncode("ß");
这是因为 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);
输出以下内容:
UTF8 Ecoded: %c3%9f
1252 Ecoded: %df
当然,在 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();
将输出以下内容:
UTF8 Ecoded: %c4%b8, round-trip = True
1252 Ecoded: %3f, round-trip = False
您可以在后面的示例中看到编码是“%3f”,它在未编码时等于问号“?”,而不是输入字符 312 (0x138)。
简而言之,将“ß”编码为“%c3%9f”并没有错,相反,它是正确的表示。但是,如果您必须具有编码“%DF”才能使远程服务器正确解码,请使用所示的 1252 代码页。
ß
字符的编码方式与使用%c3%9f
UTF-8 编码时一样。如果可能的话,这是你应该使用的。
如果您的目标网络服务器使用其他编码,您需要确切地知道那是什么编码。因为您想将该字符编码为%df
可能是Windows-1252或Windows-1250(或可能其他)的字符。
如果您确定这是您想要做的,您可以使用(假设 Windows-1252):
HttpUtility.UrlEncode("ß", Encoding.GetEncoding(1252))