问题:
HttpUtility.HtmlDecode ,HttpUtility.HtmlEncode 与 Server.HtmlDecode ,Server.HtmlEncode 与 HttpServerUtility.HtmlDecode , HttpServerUtility.HtmlEncode 有什么区别?
他们与下面一般手工写的代码有什么不一样的?
publicstaticstringhtmlencode(stringstr)
{if(str ==null|| str == "")return"";
str = str.Replace(">", ">");
str = str.Replace("<", "<");
str = str.Replace("", " ");
str = str.Replace("", " ");
str = str.Replace("\"", """);
str = str.Replace("\'", "'");
str = str.Replace("\n", "<br/>");returnstr;
}
答案:
HtmlEncode: 将 Html 源文件中不允许出现的字符进行编码,通常是编码以下字符"<"、">"、"&" 等。
HtmlDecode: 刚好跟 HtmlEncode 相关,解码出来原本的字符。
HttpServerUtility 实体类的 HtmlEncode 方法 是一种简便方式,用于在运行时从 ASP.NET Web 应用程序访问 System.Web.HttpUtility.HtmlEncode 方法。HttpServerUtility 实体类的 HtmlEncode 方法 在内部使用 System.Web.HttpUtility.HtmlEncode 对字符串进行编码。
Server.HtmlEncode 其实就是 System.Web.UI.Page 类封装的 HttpServerUtility 实体类的 HtmlEncode 方法; System.Web.UI.Page 类有这样的一个属性: public HttpServerUtility Server { get; }
所以我们可以认为:
Server.HtmlDecode = HttpServerUtility 实体类的 HtmlDecode 方法 = HttpUtility.HtmlDecode ;
Server.HtmlEncode = HttpServerUtility 实体类的 HtmlEncode 方法 = HttpUtility.HtmlEncode ;
他们只不过是为了调用方便,做了封装而已。
在 ASP 中, Server.HTMLEncode Method 过滤的字符描述如下:
如果字符串不是 DBCS 编码。这个方法将转换下面字符:
less-than character (<) | < |
greater-than character (>) | > |
ampersand character (&) | & |
double-quote character (") | " |
Any ASCII code character whose code is greater-than or equal to 0x80 | &#<number>, where <number> is the ASCII character value. |
如果是 DBCS 编码
- All extended characters are converted.
- Any ASCII code character whose code is greater-than or equal to 0x80 is converted to &#<number>, where <number> is the ASCII character value.
- Half-width Katakana characters in the Japanese code page are not converted.
在ASP.net 中情况也类似
下面是一个简单的替换测试代码,测试结果看之后的注释:
protectedvoidPage_Load(objectsender, EventArgs e)
{
TestChar("<");// 小于号 替换 <TestChar(">");// 大于号 替换 >TestChar("'");// 单引号 替换 'TestChar("");// 半角英文空格 不做替换TestChar("");// 全角中文空格 不做替换TestChar("&");// & 替换 &TestChar("\"");// 英文双引号 替换 "TestChar("\n");// 回车 不做替换TestChar("\r");// 回车 不做替换TestChar("\r\n");// 回车 不做替换}publicvoidTestChar(stringt)
{
Response.Write(Server.HtmlEncode(t));
Response.Write("__");
Response.Write(HttpUtility.HtmlEncode(t));
Response.Write("<br />");
}
所以上面我们提到的常用替换方式还是非常有用的,他还处理了一些 HttpUtility.HtmlEncode 不支持的替换。
publicstaticstringhtmlencode(stringstr)
{if(str ==null|| str == "")