在 .Net 4.5+ 中使用 WebUtility
只是为了格式化,我将其作为答案提交。
找不到任何很好的示例来比较它们,因此:
string testString = "http://test# space 123/text?var=val&another=two";
Console.WriteLine("UrlEncode: " + System.Web.HttpUtility.UrlEncode(testString));
Console.WriteLine("EscapeUriString: " + Uri.EscapeUriString(testString));
Console.WriteLine("EscapeDataString: " + Uri.EscapeDataString(testString));
Console.WriteLine("EscapeDataReplace: " + Uri.EscapeDataString(testString).Replace("%20", "+"));
Console.WriteLine("HtmlEncode: " + System.Web.HttpUtility.HtmlEncode(testString));
Console.WriteLine("UrlPathEncode: " + System.Web.HttpUtility.UrlPathEncode(testString));
//.Net 4.0+
Console.WriteLine("WebUtility.HtmlEncode: " + WebUtility.HtmlEncode(testString));
//.Net 4.5+
Console.WriteLine("WebUtility.UrlEncode: " + WebUtility.UrlEncode(testString));
输出:
UrlEncode: http%3a%2f%2ftest%23+space+123%2ftext%3fvar%3dval%26another%3dtwo
EscapeUriString: http://test#%20space%20123/text?var=val&another=two
EscapeDataString: http%3A%2F%2Ftest%23%20space%20123%2Ftext%3Fvar%3Dval%26another%3Dtwo
EscapeDataReplace: http%3A%2F%2Ftest%23+space+123%2Ftext%3Fvar%3Dval%26another%3Dtwo
HtmlEncode: http://test# space 123/text?var=val&another=two
UrlPathEncode: http://test#%20space%20123/text?var=val&another=two
//.Net 4.0+
WebUtility.HtmlEncode: http://test# space 123/text?var=val&another=two
//.Net 4.5+
WebUtility.UrlEncode: http%3A%2F%2Ftest%23+space+123%2Ftext%3Fvar%3Dval%26another%3Dtwo
在 .Net 4.5+ 中使用 WebUtility
.UrlEncode
对于更常见的字符, HttpUtility.UrlEncode
这似乎重复了
Uri.EscapeDataString(testString).Replace("%20", "+").Replace("'", "%27").Replace("~", "%7E")
注意: EscapeUriString
将保留有效的 uri 字符串,这会导致它使用尽可能多的纯文本字符。
请参阅此答案以了解比较各种编码的表格:
https://.com/a/11236038/555798
换行符 此处列出的所有换行符(除 外 HttpUtility.HtmlEncode
)都将转换 "\n\r"
为 %0a%0d
或 %0A%0D
请随意编辑此内容并将新字符添加到我的测试字符串中,或者将它们留在评论中,然后我会对其进行编辑。