除“&"符号外,还应在HTML href/src属性中编码其他哪些字符? [英] What other characters beside ampersand (&) should be encoded in HTML href/src attributes?
问题描述
&"号是唯一应在HTML属性中编码的字符吗?
Is the ampersand the only character that should be encoded in an HTML attribute?
众所周知,这不会通过验证:
It's well known that this won't pass validation:
<a href="http://domain.com/search?q=whatever&lang=en"></a>
Because the ampersand should be &
. Here's a direct link to the validation fail.
此人列出了一堆应该编码的字符,但他错了.如果您在http://
中对第一个"/"进行编码,则href将无法正常工作.
This guy lists a bunch of characters that should be encoded, but he's wrong. If you encode the first "/" in http://
the href won't work.
在ASP.NET中,是否已经建立了一个帮助程序来处理此问题?像Server.UrlEncode和HtmlEncode这样的东西显然不起作用-它们用于不同的目的.
In ASP.NET, is there a helper method already built to handle this? Stuff like Server.UrlEncode and HtmlEncode obviously don't work - those are for different purposes.
我可以构建自己的简单扩展方法(例如.ToAttributeView()
),该方法可以进行简单的字符串替换.
I can build my own simple extension method (like .ToAttributeView()
) which does a simple string replace.
推荐答案
除值的标准URI编码之外,&是您唯一需要担心的与HTML实体相关的唯一字符,因为这是每个HTML实体开头的字符.例如以下URL:
Other than standard URI encoding of the values, & is the only character related to HTML entities that you have to worry about simply because this is the character that begins every HTML entity. Take for example the following URL:
http://query.com/?q=foo<=bar>=baz
即使没有尾随的分号,因为& lt;是<的实体和& gt;是>的实体,某些旧的浏览器会将此URL转换为:
Even though there aren't trailing semi-colons, since < is the entity for < and > is the entity for >, some old browsers would translate this URL to:
http://query.com/?q=foo<=bar>=baz
因此您需要指定&作为& amp;以防止HTML解析文档中的链接发生这种情况.
So you need to specify & as & to prevent this from occurring for links within an HTML parsed document.
这篇关于除“&"符号外,还应在HTML href/src属性中编码其他哪些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!