C# .net 几种HtmlEncode,HtmlDecode的区别

article/2025/10/12 5:27:01

 

一、C#中的编码

HttpUtility.HtmlDecode、HttpUtility.HtmlEncode与Server.HtmlDecode、Server.HtmlEncode与HttpServerUtility.HtmlDecode、HttpServerUtility.HtmlEncode的区别?

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

 

[c-sharp] view plaincopy

 

  1. public static string htmlencode(string str)  
  2. {  
  3.     if (str == null || str == "")  
  4.         return "";  
  5.   
  6.     str.Replace("<", "<");  
  7.     str.Replace(">", ">");  
  8.     str.Replace(" ", " ");  
  9.     str.Replace(" ", "  ");  
  10.     str.Replace("/"", """);  
  11.     str.Replace("/'", "'");  
  12.     str.Replace("/n", "<br/>");  
  13.   
  14.     return str;  
  15. }  

 

答案:

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;

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

 

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

 

[c-sharp] view plaincopy

 

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     TestChar("<");   //小于号        替换为      <         
  4.     TestChar(">");   //大于号        替换为      >  
  5.     TestChar(" ");    //英文半角空格        替换为      不做替换;  
  6.     TestChar(" ");  //中文全角空格        替换为      不做替换;  
  7.     TestChar("&");   //&        替换为      &  
  8.     TestChar("/'");   //单引号        替换为      ';  
  9.     TestChar("/"");   //双引号        替换为      "  
  10.     TestChar("/r");   //回车        替换为      不做替换;  
  11.     TestChar("/n");   //回车        替换为      不做替换;  
  12.     TestChar("/r/n");   //回车        替换为      不做替换;  
  13. }  
  14. protected void TestChar(String str)  
  15. {  
  16.     Response.Write(Server.HtmlEncode(str));  
  17.     Response.Write("----------------------");  
  18.     Response.Write(HttpUility.HtmlEncode(str));  
  19.     Response.Write("<br/>");  
  20. }  

 

 

 

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

 

[c-sharp] view plaincopy

 

  1. public static string htmlencode(string str)  
  2. {  
  3.     str.Replace("<", "<");  
  4.     str.Replace(">", ">");  
  5.     str.Replace(" ", " ");  
  6.     str.Replace(" ", " ");  
  7.     str.Replace("/'", "'");  
  8.     str.Replace("/"", """);  
  9.     str.Replace("/n", "<br/>");  
  10. }  

 

 

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

 

[c-sharp] view plaincopy

 

  1. public static unsafe void HtmlEncode(string value, TextWriter output)  
  2. {  
  3.     if (value != null)  
  4.     {  
  5.         if (output == null)  
  6.         {  
  7.             throw new ArgumentNullException("output");  
  8.         }  
  9.         int num = IndexOfHtmlEncodingChars(value, 0);  
  10.         if (num == -1)  
  11.         {  
  12.             output.Write(value);  
  13.         }  
  14.         else  
  15.         {  
  16.             int num2 = value.Length - num;  
  17.             fixed (char* str = ((char*) value))  
  18.             {  
  19.                 char* chPtr = str;  
  20.                 char* chPtr2 = chPtr;  
  21.                 while (num-- > 0)  
  22.                 {  
  23.                     chPtr2++;  
  24.                     output.Write(chPtr2[0]);  
  25.                 }  
  26.                 while (num2-- > 0)  
  27.                 {  
  28.                     chPtr2++;  
  29.                     char ch = chPtr2[0];  
  30.                     if (ch <= '>')  
  31.                     {  
  32.                         switch (ch)  
  33.                         {  
  34.                             case '&':  
  35.                             {  
  36.                                 output.Write("&");  
  37.                                 continue;  
  38.                             }  
  39.                             case '/'':  
  40.                             {  
  41.                                 output.Write("'");  
  42.                                 continue;  
  43.                             }  
  44.                             case '"':  
  45.                             {  
  46.                                 output.Write(""");  
  47.                                 continue;  
  48.                             }  
  49.                             case '<':  
  50.                             {  
  51.                                 output.Write("<");  
  52.                                 continue;  
  53.                             }  
  54.                             case '>':  
  55.                             {  
  56.                                 output.Write(">");  
  57.                                 continue;  
  58.                             }  
  59.                         }  
  60.                         output.Write(ch);  
  61.                         continue;  
  62.                     }  
  63.                     if ((ch >= '/x00a0') && (ch < 'ā'))  
  64.                     {  
  65.                         output.Write("&#");  
  66.                         output.Write(((int) ch).ToString(NumberFormatInfo.InvariantInfo));  
  67.                         output.Write(';');  
  68.                     }  
  69.                     else  
  70.                     {  
  71.                         output.Write(ch);  
  72.                     }  
  73.                 }  
  74.             }  
  75.         }  
  76.     }  
  77. }   

 

 

二、JS中的编码和解码

 

[c-sharp] view plaincopy

 

  1. 一、escape/unescape  
  2.     escape:escape 方法返回一个包含 charstring 内容的字符串值(Unicode 格式)。所有空格、标点、 重音符号以及任何其他非 ASCII 字符都用 %xx 编码替换,其中 xx 等于表示该字符的十六进制数  
  3.     unescape:从用 escape 方法编码的 String 对象中返回已解码的字符串  
  4.     例外字符: @ * / +  
  5.   
  6. 二、encodeURI/decodeURI  
  7.     encodeURI:方法返回一个已编码的 URI。如果将编码结果传递给 decodeURI,则将返回初始的字符串。encodeURI 不对下列字符进行编码:“:”、“/”、“;”和“?”。请使用 encodeURIComponent 对这些字符进行编码  
  8.     decodeURI:从用encodeURI方法编码的String对象中返回已解码的字符串  
  9.     例外字符:! @ # $ & * ( ) = : / ; ? + '  
  10.   
  11. 三、encodeURIComponent/decodeURIComponent  
  12.     encodeURIComponent:encodeURIComponent 方法返回一个已编码的 URI。如果将编码结果传递给decodeURIComponent,则将返回初始的字符串。因为 encodeURIComponent 方法将对所有字符编码  
  13.     decodeURIComponent:从用encodeURIComponent方法编码的String对象中返回已解码的字符串  
  14.     例外字符:! * ( ) '  

 

 

 

.NET编码解码(HtmlEncode与HtmlEncode)

编码代码:

System.Web.HttpUtility.HtmlEncode("<a href=\"http://hovertree.com/\">何问起</a>");

解码代码:

System.Web.HttpUtility.HtmlDecode("&lt;a href=&quot;http://hovertree.com/&quot;&gt;&#20309;&#38382;&#36215;&lt;/a&gt; "); 

效果体验:http://tool.hovertree.com/htmlcode/

本工具还可以实现Unicode解码,例如可以把以下代码解码试试:
 

&#60;&#97;&#32;&#104;&#114;&#101;&#102;&#61;&#34;&#104;&#116;&#116;&#112;&#58;&#47;&#47;&#104;&#111;&#118;&#101;&#114;&#116;&#114;&#101;&#101;&#46;&#99;&#111;&#109;&#47;&#34;&#62;&#20309;&#38382;&#36215;&#65292;&#25105;&#29233;&#20320;&#65292;&#23601;&#20687;&#32769;&#40736;&#29233;&#22823;&#31859;&#12290;&#60;&#47;&#97;&#62;&#32;

 

详细实现:


Default.aspx

复制代码

<%@ Page ValidateRequest="false" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="test_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>asp.net(C#) 编码解码(HtmlEncode与HtmlEncode)- 何问起</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblShow" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="txtInput" runat="server" Height="194px" TextMode="MultiLine" Width="305px"></asp:TextBox>
<asp:Button ID="btnOk" runat="server" Text="提交" OnClick="btnOk_Click" /></div>
</form>
</body>
</html>

复制代码

Default.aspx.cs

复制代码

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/***********************编码研究***********************
* 1.默认情况是不允许用户在TextBox中输入html标签的,
* 如果需要输入,设置Page的ValidateRequest="false"
* 2.可以把输入的html标签,比如<input>直接存放在数据库中,
* 只是在输出的时候编码,防止原样输出打乱页面布局.或者呈现html元素.
*****************************************************/
public partial class test_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// http://sosoft.cnblogs.com/
}
protected void btnOk_Click(object sender, EventArgs e)
{
lblShow.Text = htmlEncode(txtInput.Text);
} 
/// <summary>
/// 对输入的html编码,同时对回车与空格进行转换
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string htmlEncode(string str)
{
return Server.HtmlEncode(str).Replace("\n", "<br/>").Replace(" ", " ");
}}

复制代码


http://chatgpt.dhexx.cn/article/nuvdbgnW.shtml

相关文章

【C#】C#中的HtmlEncode与HtmlDecode:HttpUtility.HtmlEncode,Server.HtmlEncode,WebUtility.HtmlEncode

HtmlEncode(String) 将字符串转换为 HTML 编码字符串。 HtmlDecode(String) 将已经为 HTTP 传输进行过 HTML 编码的字符串转换为已解码的字符串。 在web端项目中通常使用HttpUtility.HtmlEecode&#xff0c;HttpUtility.HtmlDecode&#xff0c;Server.HtmlEncode&#xff0c;Se…

js htmlEncode

javascript处理HTML的Encode(转码)和Decode(解码)总结 HTML的Encode(转码)和解码(Decode)在平时的开发中也是经常要处理的&#xff0c;在这里总结了使用javascript处理HTML的Encode(转码)和解码(Decode)的常用方式 一、用浏览器内部转换器实现转换 1.1.用浏览器内部转换器实现…

READNE.md 语法

标题列表引用代码块链接图片分割线表格 1. 标题 # 一级标题 ## 二级标题 ### 三级标题 #### 四级标题 ##### 五级标题 ###### 六级标题 2. 列表 2.1 有序列表 直接在前面写数字序号&#xff1a; 1. a 2. bc 3. 1234 2.2 无序列表 有三种方式&#xff1a;""、&qu…

# 今天要讲一下我所用的md语法

今天要讲一下我所用的md语法 首先md是一种标记语言&#xff0c;我们不要把它想的过于复杂&#xff0c;其实对于经常探索新知识的人来说上手速度非常快。 下面讲一下基本语法 标题语法 一级标题&#xff1a;# Heading level 1二级标题&#xff1a;## Heading level 2二级标题&…

.MD语法入门,教你写好readme文档

.md即markdown文件的基本常用编写语法,是一种快速标记、快速排版语言&#xff0c;现在很多前段项目中的说明文件readme等都是用.md文件编写的&#xff0c;而且很多企业也在在鼓励使用这种编辑方式&#xff0c;特别作为一个前端从业者更要学会使用这种语言。下面就简单和大家分享…

编辑MD文件的语法格式

这里写自定义目录标题 欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题&#xff0c;有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants 创建一个自定义列表如何创建一个…

.md,markdown文件的基本常用编写语法

序言&#xff1a; 很久没有写博客了&#xff0c;感觉只要是不写博客&#xff0c;人就很变得很懒&#xff0c;学的知识点感觉还是记不住&#xff0c;渐渐地让我明白&#xff0c;看的越多&#xff0c;懂的越少&#xff08;你这话不是有毛病吗&#xff1f;应该是看的越多&#xff…

.md即markdown文件常用语法

参阅cmd版官网&#xff1a;markdown 参考博文&#xff1a;Markdown语法介绍&#xff08;详细&#xff09; 1.标题 使用#符号包起来&#xff0c;符号和内容中间空格可省略&#xff0c;尾部#号可省略。依次1~6级标题&#xff0c;对应html中的h1~6标签 会使上一行成为一级标题&…

.md文件的常用语法

正文&#xff1a; 1、标题的几种写法&#xff1a; 第一种&#xff1a; 前面带#号&#xff0c;后面带文字&#xff0c;分别表示h1-h6,上图可以看出&#xff0c;只到h6&#xff0c;而且h1下面会有一条横线&#xff0c;注意&#xff0c;#号后面有空格 第二种&#xff1a; 这种方…

README.md 文件的作用和语法

一、README.md 文件的作用 md文件一般出现在项目的根目录下面&#xff0c;其作用是&#xff1a;对项目的主要信息进行描述。 如果一个项目你很长时间都没有动&#xff0c;突然你需要修改这个项目&#xff0c;那么通过README.md中对项目的描述能让你快速的再次上手&#xff1b;或…

md文档编写语法

md文档编写语法 一、标题 语法&#xff1a;#后面跟空格&#xff0c;再加文字&#xff0c;几级就加几个# 例如&#xff1a; 这是一级标题&#xff08;# 这是一级标题&#xff09; 这是二级标题&#xff08;## 这是二级标题&#xff09; 这是三级标题 这是四级标题 二、字体…

常用md语法

基本要素 # 一级标题 ## 二级标题 ### 三级标题 #### 四级标题 ##### 五级标题 ###### 六级标题一级标题 二级标题 三级标题 四级标题 五级标题 六级标题 分隔线 三个或更多的-表示分隔线 ---*斜体*斜体 **粗体**粗体 ***粗斜体***粗斜体 删除横线 ~~删除横线~~删除…

md基础语法总结

md即为Markdown,Markdown的目标是实现「易读易写」,可读性,无论如何,都是最重要的。其实md的底层最终还是将我们写的语法转化为html标签了 --------------------------------下面开始------------------------------------ 1.标题 # H1## H2### H3#### H4##### H5###### H6…

Markdown(MD)文档语法使用指南(学会后写文档写博客贼6)

文章目录 标题代码块多行代码块单行代码块 列表有序列表无序列表 图片链接分割线引用表格斜体、加粗、下划线、删除线 Markdown 是一种用来写作的轻量级「标记语言」&#xff0c;它用简洁的语法代替排版&#xff0c;而不像一般我们用的字处理软件 Word 或 Pages 有大量的排版、…

.md文件格式语法详解,即markdown文件语法详解(图文并茂)

相关链接&#xff1a; 官网地址博客地址。截图博客地址。markdown版本&#xff0c;点击编辑源码地址。需IDEA克隆代码&#xff0c;用IDEA打开 Markdown 是一种轻量级的标记语言&#xff0c;本质是html。不同应用对md的支持度不一致(方言)&#xff0c;需要注意。 0.目录&…

md基本语法介绍

发现很多人都喜欢用.md&#xff08;markdown&#xff09;进行项目说明&#xff0c;眼馋其方便快捷的实用性&#xff0c;也学习一下&#xff0c;做个简单的笔记 1、标题修饰符 ‘#’ 标题分为h1~h6以#为标识符&#xff0c;#号的多少划分等级,而且仅有h1,h2是有下划线的&#xf…

Markdown最详细的语法教程,.md文件解读

.md即markdown文件的基本常用编写语法,是一种快速标记、快速排版语言&#xff0c;现在很多前段项目中的说明文件readme等都是用.md文件编写的&#xff0c;而且很多企业也在在鼓励使用这种编辑方式&#xff0c;特别作为一个前端从业者更要学会使用这种语言。 当然这种语言更适合…

.md 基本常用编写语法

.md文件基本常用编写语法 1.标题 第一种&#xff1a; # 一级标题 ## 二级标题 ### 三级标题 #### 四级标题 ##### 五级标题 ###### 六级标题一级标题 二级标题 三级标题 四级标题 五级标题 六级标题 ​ 前面带#号&#xff0c;后面带文字&#xff0c;分别表示h1-h6,上图…

MD语法 官方参考

这里写自定义目录标题 欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题&#xff0c;有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants 创建一个自定义列表如何创建一个…

【md】1.markdown基础语法

一、基本文本使用 不是程序员的话&#xff0c;推荐只看本部分。后续的操作虽然也会用到部分&#xff0c;但频率很低&#xff0c;用的时候直接从目录跳转即可。 1、换行 直接回车。 2、段落 &#xff08;1&#xff09;、格式 换行两次 &#xff08;2&#xff09;、区别富…