नमोऽमिताभा 独善其身 兼济天下

HtmlEncode

下面是一个简单的替换测试代码,测试结果看之后的注释:

protected void Page_Load(object sender, EventArgs e)
{

TestChar("<"); // 小于号 替换 <
TestChar(">"); // 大于号 替换 >
TestChar("'"); // 单引号 替换 '
TestChar(" "); // 半角英文空格 不做替换
TestChar(" "); // 全角中文空格 不做替换
TestChar("&"); // & 替换 &
TestChar("\""); // 英文双引号 替换 "
TestChar("\n"); // 回车 不做替换
TestChar("\r"); // 回车 不做替换
TestChar("\r\n"); // 回车 不做替换
}


public void TestChar(string t)
{
Response.Write(Server.HtmlEncode(t));
Response.Write("__");
Response.Write(HttpUtility.HtmlEncode(t));
Response.Write("
");
}所以上面我们提到的常用替换方式还是非常有用的,他还处理了一些 HttpUtility.HtmlEncode 不支持的替换。

public static string htmlencode(string str)
{
if (str == null || str == "")
return "";
str = str.Replace(">", ">");
str = str.Replace(" <", "<");
str = str.Replace(" ", " "); // HttpUtility.HtmlEncode( 并不支持这个替换
str = str.Replace(" ", "  "); // HttpUtility.HtmlEncode( 并不支持这个替换
str = str.Replace("\"", """);
str = str.Replace("\'", "'");
str = str.Replace("\n", "
"); // HttpUtility.HtmlEncode( 并不支持这个替换
return str;
}我们使用 Reflector 查看 HttpUtility.HtmlEncode 的实现,我们就可以看到,它只考虑的五种情况,空格,回车是没有处理的:

使用 Reflector 查看 HttpUtility.HtmlEncode 实现代码其中最重要的代码如下:

public static unsafe void HtmlEncode(string value, TextWriter output)
{
if (value != null)
{
if (output == null)
{
throw new ArgumentNullException("output");
}
int num = IndexOfHtmlEncodingChars(value, 0);
if (num == -1)
{
output.Write(value);
}
else
{
int num2 = value.Length - num;
fixed (char* str = ((char*) value))
{
char* chPtr = str;
char* chPtr2 = chPtr;
while (num-- > 0)
{
chPtr2++;
output.Write(chPtr2[0]);
}
while (num2-- > 0)
{
chPtr2++;
char ch = chPtr2[0];
if (ch <= '>')
{
switch (ch)
{
case '&':
{
output.Write("&");
continue;
}
case '\'':
{
output.Write("'");
continue;
}
case '"':
{
output.Write(""");
continue;
}
case '<':
{
output.Write("<");
continue;
}
case '>':
{
output.Write(">");
continue;
}
}
output.Write(ch);
continue;
}
if ((ch >= '\x00a0') && (ch < 'ā'))
{
output.Write("&#");
output.Write(((int) ch).ToString(NumberFormatInfo.InvariantInfo));
output.Write(';');
}
else
{
output.Write(ch);
}
}
}
}
}
}