c# - 为什么渲染属性时需要转义 < 和 & ?

标签 c# html asp.net .net

我正在阅读 HtmlAttributeEncode 的文档,据我了解,它的目的是在渲染双引号内作为属性出现的 HTML 时使用,例如

<INPUT Value="This value must be escaped so that it doesn't contain any quotes">

据我所知,我唯一需要转义的字符是双引号。浏览器应该能够找出该字符串中属于该属性的所有其他内容。

那么,为什么文档这么说呢?

The HtmlAttributeEncode method converts only quotation marks ("), ampersands (&), and left angle brackets (<) to equivalent character entities. It is considerably faster than the HtmlEncode method.

事实上它确实逃脱了这些,正如 this poor guy 所示。 .

在这种情况下有什么理由转义 < 和 & 字符吗?这是 HTML5 规范所要求的吗?

用我的肉眼,我可以轻松地看到此字符序列中定界的开始和结束位置:

<INPUT value="You & I can both easily see that 5 < 6!">

只要双引号序列正确闭合(并且双引号被转义),我不明白为什么其他字符必须进行 HTML 编码。

最佳答案

从规范来看:

3.2.3.1 Attributes

Except where otherwise specified, attributes on HTML elements may have any string value, including the empty string. Except where explicitly stated, there is no restriction on what text can be specified in such attributes.

根据specs of html4value属性的内容应为cdata类型。

来自HTML Document Representation :

5.3.2 Character entity references

Four character entity references deserve special mention since they are frequently used to escape special characters:

"&lt;" represents the < sign.
"&gt;" represents the > sign.
"&amp;" represents the & sign.
"&quot;" represents the " mark.

Authors wishing to put the "<" character in text should use "&lt;" (ASCII decimal 60) to avoid possible confusion with the beginning of a tag (start tag open delimiter). Similarly, authors should use "&gt;" (ASCII decimal 62) in text instead of ">" to avoid problems with older user agents that incorrectly perceive this as the end of a tag (tag close delimiter) when it appears in quoted attribute values.

Authors should use "&" (ASCII decimal 38) instead of "&" to avoid confusion with the beginning of a character reference (entity reference open delimiter). Authors should also use "&" in attribute values since character references are allowed within CDATA attribute values.

关于c# - 为什么渲染属性时需要转义 < 和 & ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41454024/

相关文章:

c# - 将类型为 `Kendo.Mvc.UI.DataSourceRequest` 的对象从 jquery 传递到 Mvc Action

javascript - 如何将indexedDB游标结果绑定(bind)到自动完成输入框

html - 如何在页面底部创建一个通知栏?

asp.net - UpdatePanel 内 FormView 中的 FileUpload

c# - 如何在 MVC 3 中获取当前页面 URL

asp.net - Redis 框架的服务堆栈许可证

c# - NHibernate Native SQL 多重连接

c# - 将 GET 变量挂接到 onload JavaScript 事件中

c# - PutBlock 能否用于附加到 Azure 中的现有 BlockBlob

jquery - 下拉菜单消失和回来只在IE7问题