使用 C# 对每个 utf-8 字符进行百分比编码

use*_*221 3 c# url-encoding percent-encoding

我想准备一个字符串,将其放入“post”请求中。不幸的是,我发现的所有对 url 进行编码的方法似乎都只对少数字符应用百分比编码。各种方法,例如。HttpUtility.UrlEncode,保留一些字符,例如 () 和 \xc2\xa7 不变。

\n

Thy*_*ine 5

这是您正在寻找的吗?

\n\n
string input = @"such as () and \xc2\xa7 untouched.";\n//Console.WriteLine(input);\nConsole.WriteLine(HttpUtility.UrlEncodeUnicode(input));\nConsole.WriteLine(HttpUtility.UrlEncode(input));\nstring everything = string.Join("", input.ToCharArray().Select(c => "%" + ((int)c).ToString("x2")).ToArray());\nConsole.WriteLine(everything);\nConsole.WriteLine(HttpUtility.UrlDecode(everything));\n\n//This is my understanding of what you\'re asking for:\nstring everythingU = string.Join("", input.ToCharArray().Select(c => "%u" + ((int)c).ToString("x4")).ToArray());\nConsole.WriteLine(everythingU);\nConsole.WriteLine(HttpUtility.UrlDecode(everythingU));\n
Run Code Online (Sandbox Code Playgroud)\n\n

其输出:

\n\n
such+as+()+and+%u00a7+untouched.\nsuch+as+()+and+%c2%a7+untouched.\n%73%75%63%68%20%61%73%20%28%29%20%61%6e%64%20%a7%20%75%6e%74%6f%75%63%68%65%64%2e\nsuch as () and \xef\xbf\xbd untouched.\n\n%u0073%u0075%u0063%u0068%u0020%u0061%u0073%u0020%u0028%u0029%u0020%u0061%u006e%u0064%u0020%u00a7%u0020%u0075%u006e%u0074%u006f%u0075%u0063%u0068%u0065%u0064%u002e\nsuch as () and \xc2\xa7 untouched.\n
Run Code Online (Sandbox Code Playgroud)\n