几种HtmlEncode的区别

本文详细介绍了C#中的HtmlEncode与HtmlDecode方法的区别及其与手工替换代码的不同,并对比了JavaScript中的escape/unescape、encodeURI/decodeURI及encodeURIComponent/decodeURIComponent方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、C#中的编码

HttpUtility.HtmlDecodeHttpUtility.HtmlEncodeServer.HtmlDecode、Server.HtmlEncodeHttpServerUtility.HtmlDecode、HttpServerUtility.HtmlEncode的区别?

它们与下面一般手工写的代码有什么区别?

答案:

HtmlEncode:是将html源文件中不容许出现的字符进行编码,通常是编码以下字符:"<"、">"、"&"、"""、"'"等;

HtmlDecode:跟HtmlEncode恰好相反,是解码出原来的字符;

 

HttpServerUtility实体类的HtmlEncode(HtmlDecode)的简便方式,用于在运行时从ASP.NET Web应用程序访问System.Web.HttpUtility.HtmlEncode(HtmlDecode)方法,HttpServerUtility实体类的HtmlEncode(HtmlDecode)方法在内部是使用System.Web.HttpUtility.HtmlEncode(HtmlDecode)方法对字符进行编码(解码)的;

 

 

Server.HtmlEncode(Server.HtmlDecode)其实是System.Web.UI.Page类封装了HttpServerUtility实体类的HtmlEncode(HtmlDecode)的方法;

System.Web.UI.Page类有这样一个属性:public HttpServerUtility Server{get;}

 

 

所以可以认为:

Server.HtmlEncode=HttpServerUtility实体类的HtmlEncode方法=HttpUtility.HtmlEncode;

Server.HtmlDecode=HttpServerUtility实体类的HtmlDecode方法=HttpUtility.HtmlDecode;

它们只不过是为了调用方便,进行了封装而已;

 

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

 

 

所以手工的替换方法还是很有必要的,处理一些HtmlEncode不支持的替换。

 

使用Reflector 查看 HttpUttility.HtmlEncode 的实现,我们就可以看到,它只考虑的五种情况,空格,回车是没有处理的:

 

二、JS中的编码和解码

本文摘自:http://blog.joycode.com/ghj/archives/2010/02/26/115894.joy

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值