几种 HtmlEncode 的区别(转发)

问题:

HttpUtility.HtmlDecode ,HttpUtility.HtmlEncode  与  Server.HtmlDecode ,Server.HtmlEncode  与 HttpServerUtility.HtmlDecode , HttpServerUtility.HtmlEncode 有什么区别?

他们与下面一般手工写的代码有什么不一样的?

public static string htmlencode(string str)
 {
        if (str == null || str == "")
            return "";
        str = str.Replace(">", ">");
        str = str.Replace(" <", "&lt;");
        str = str.Replace(" ", "&nbsp;");
        str = str.Replace("  ", " &nbsp;");
        str = str.Replace("\"", "&quot;");
        str = str.Replace("\‘", "‘");
        str = str.Replace("\n", " <br/> ");
        return str;
}

答案:

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 (<) &lt;
greater-than character (>) &gt;
ampersand character (&) &amp;
double-quote character (") &quot;
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.

相关资料:

Server.HTMLEncode Method

http://msdn.microsoft.com/en-us/library/ms525347.aspx

在ASP.net 中情况也类似

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

protected void Page_Load(object sender, EventArgs e)
{

    TestChar("<"); // 小于号    替换   &lt;
    TestChar(">"); // 大于号    替换   &gt;
    TestChar("‘"); // 单引号    替换   ‘
    TestChar(" "); // 半角英文空格    不做替换
    TestChar(" "); // 全角中文空格    不做替换
    TestChar("&"); // &    替换   &amp;
    TestChar("\""); // 英文双引号    替换   &quot;
    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("<br />");
}

所以上面我们提到的常用替换方式还是非常有用的,他还处理了一些 HttpUtility.HtmlEncode 不支持的替换。

public static string htmlencode(string str)
{
    if (str == null || str == "")
        return "";
    str = str.Replace(">", "&gt;");
    str = str.Replace(" <", "&lt;");
    str = str.Replace(" ", "&nbsp;");       // HttpUtility.HtmlEncode( 并不支持这个替换
    str = str.Replace("  ", " &nbsp;");     // HttpUtility.HtmlEncode( 并不支持这个替换
    str = str.Replace("\"", "&quot;");
    str = str.Replace("\‘", "‘");
    str = str.Replace("\n", " <br/> ");     // 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("&amp;");
                                continue;
                            }
                            case ‘\‘‘:
                            {
                                output.Write("‘");
                                continue;
                            }
                            case ‘"‘:
                            {
                                output.Write("&quot;");
                                continue;
                            }
                            case ‘<‘:
                            {
                                output.Write("&lt;");
                                continue;
                            }
                            case ‘>‘:
                            {
                                output.Write("&gt;");
                                continue;
                            }
                        }
                        output.Write(ch);
                        continue;
                    }
                    if ((ch >= ‘\x00a0‘) && (ch < ‘ā‘))
                    {
                        output.Write("&#");
                        output.Write(((int) ch).ToString(NumberFormatInfo.InvariantInfo));
                        output.Write(‘;‘);
                    }
                    else
                    {
                        output.Write(ch);
                    }
                }
            }
        }
    }
} 

参考资料:

HttpUtility.HtmlDecode与Server.HtmlDecode区别

http://topic.csdn.net/u/20090220/11/110c8079-1632-418a-b43b-3ddb2f0a06e2.html

詳細解說幾個建置網站時常用的編碼方法

http://blog.miniasp.com/?tag=/htmlencode

用于 Silverlight 的 .NET Framework 类库HttpUtility.HtmlEncode 方法

http://msdn.microsoft.com/zh-cn/library/system.windows.browser.httputility.htmlencode(VS.95).aspx

HttpUtility.HtmlEncode() and HttpServerUtility.HtmlEncode() do not encode all non-ASCII characters

https://connect.microsoft.com/VisualStudio/feedback/details/102251/httputility-htmlencode-and-httpserverutility-htmlencode-do-not-encode-all-non-ascii-characters?wa=wsignin1.0

转自:http://blog.joycode.com/ghj/archives/2010/02/26/115894.joy

时间: 2024-07-29 06:31:59

几种 HtmlEncode 的区别(转发)的相关文章

几种HtmlEncode的区别(转)

一.C#中的编码 HttpUtility.HtmlDecode.HttpUtility.HtmlEncode与Server.HtmlDecode.Server.HtmlEncode与HttpServerUtility.HtmlDecode.HttpServerUtility.HtmlEncode的区别? 它们与下面一般手工写的代码有什么区别? public static string htmlencode(string str) { if (str == null || str == "&quo

(转)几种HtmlEncode的区别

一.C#中的编码 HttpUtility.HtmlDecode.HttpUtility.HtmlEncode与Server.HtmlDecode.Server.HtmlEncode与HttpServerUtility.HtmlDecode.HttpServerUtility.HtmlEncode的区别? 它们与下面一般手工写的代码有什么区别? [c-sharp] view plaincopy public static string htmlencode(string str) { if (st

虚拟机NetworkAdapter三种方式的区别

虚拟机在安装时默认的有三块网卡,VMnet1和VMnet8,另外还有VMnet0 Vmware 还提供了三种网络连接模式: 分别为: A 桥接bridge  B NAT 网络地址转换 C  主机模式 下面来简单说一下 三种方式的区别  : 1) bridge : 默认使用VMnet0,不提供DHCP服务 在桥接模式下,虚拟机和宿主计算机处于同等地位,虚拟机就像是一台真实主机一样存在于局域网中.因此在桥接模式下,我们就要像对待其他真实计算机一样为其配置IP.网关.子网掩码等等.当我们可以自由分配局

UIImage两种初始化的区别

UIImage可以通过以下两种方式进行初始化: 1 //第一种初始化方式:[注意使用这种初始化的时候如果是png格式的可以不给后缀名,根据屏幕的的分辨率去匹配图片] 2 UIImage *image = [UIImage imageNamed:@"v_red_heart_selected"]; 1 //第二种初始化方式:[必须拼接图片的全名称,否则image的路径为空] 2 NSString *filePath = [[NSBundle mainBundle] pathForResou

PHP中数组合并的两种方法及区别介绍

PHP数组合并两种方法及区别 如果是关联数组,如下: 复制代码代码如下: $a = array( 'where' => 'uid=1', 'order' => 'uid', ); $b = array( 'where' => 'uid=2', 'order' => 'uid desc', ); 1. array_merge,如果两个数组存在相同的key,后面的一个会覆盖前面的 复制代码代码如下: <?php $c = array_merge($a, $b); var_expo

.NET中的三种Timer的区别和用法(转)

最近正好做一个WEB中定期执行的程序,而.NET中有3个不同的定时器.所以正好研究研究.这3个定时器分别是:  //1.实现按用户定义的时间间隔引发事件的计时器.此计时器最宜用于 Windows 窗体应用程序中,并且必须在窗口中使用.  System.Windows.Forms.Timer  // 2.提供以指定的时间间隔执行方法的机制.无法继承此类.  System.Threading.Timer  //3.在应用程序中生成定期事件.  System.Timers.Timer  这三个定时器位

UIimage两种初始化的区别 广告轮播封装

UIimage两种初始化的区别 第一种初始化: UIImage *image = [UIImage imageNamed:@"xxx"];  注意(这种方法加载的图片如果后缀名是png的,可以不写后缀名,根据屏幕分辨率自己去匹配图片) 第二种初始化: NSString *path = [[NSBundle mainBundle] pathForResource:@"xxx.png" ofType:nil]; UIImage *image = [[UIImage al

Activity的四种启动模式区别

(1) standard 模式启动模式,每次激活Activity时都会创建Activity,并放入任务栈中. (2) singleTop 如果在任务的栈顶正好存在该Activity的实例, 就重用该实例,否者就会创建新的实例并放入栈顶即使栈中已经存在该Activity实例,只要不在栈顶,都会创建实例. (3)singleTask 如果在栈中已经有该Activity的实例,就重用该实例.重用时,会让该实例回到栈顶,因此在它上面的实例将会被移除栈.如果栈中不存在该实例,将会创建新的实例放入栈中. (

定义c/c++全局变量/常量几种方法的区别(转载)

出自:http://www.cnblogs.com/yaozhongxiao/archive/2010/08/08/1795338.html 在讨论全局变量之前我们先要明白几个基本的概念:  1. 编译单元(模块): 在ide开发工具大行其道的今天,对于编译的一些概念很多人已经不再清楚了,很多程序员最怕的就是处理连接错误 (link error)  因为它不像编译错误那样可以给出你程序错误的具体位置,你常常对这种错误感到懊恼,但是如果你经常使用 gcc,makefile等工具在linux或者嵌入