【问题标题】:Correct Way to Encode HTML Page Title编码 HTML 页面标题的正确方法
【发布时间】:2012-08-18 01:15:43
【问题描述】:

我有一个 ASP.NET WebForms 应用程序。我正在根据我的数据库中的内容设置页面的标题。

因为此内容是由用户输入的,所以它可以包含任何字符,包括可以解释为 HTML 标记的字符。因此,我在设置标题之前对这个内容进行了 HTML 编码。

但我发现这会导致产生过度编码的结果:

<title>Hoigaard&amp;#39;s Nordic Walking Tuesdays</title>

安全编码用于设置标题标签的文本的正确方法是什么?

【问题讨论】:

  • 在设置Page.Title之前,您是否首先验证了需要对值进行编码?
  • 好吧,在文本为&lt;/title&gt;&lt;/head&gt;&lt;body&gt;... 的极端情况下,我可以看到真正的问题出现了。我不认为不编码此内容是一种好的形式。
  • 没有。我的意思是您是否确认 Page.Title 没有已经对结果进行编码?
  • 天啊!查看问题文本,我实际上可以看到它 is 编码了两次。看起来就是这个问题。谢谢。

标签: asp.net html webforms


【解决方案1】:

我对此进行了测试,似乎设置Page.Title 已经 执行编码。因此,您的额外编码会导致双重编码结果。直接设置Page.Title即可:

Page.Title = "Test & Testing";

结果:

<title>Test &amp; Testing</title>

【讨论】:

  • javascript 是什么情况??
【解决方案2】:

使用一些类似于PHP函数htmlspecialchars()的函数:

<%
' Copyright (c) 2009, reusablecode.blogspot.com; some rights reserved.
' This work is licensed under the Creative Commons Attribution License.

' Convert special characters to HTML entities.
function htmlspecialchars(someString)
    ' Critical that ampersand is converted first, since all entities contain them.
    htmlspecialchars = replace(replace(replace(replace(someString, "&", "&amp;"), ">", "&gt;"), "<", "&lt;"), """", "&quot;")
end function
%>

来源:http://snipplr.com/view/12207/htmlspecialchars/

【讨论】:

  • 看起来问题是 ASP.NET 已经对标题进行了编码,所以我对其进行了两次编码。
猜你喜欢
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
  • 2018-01-15
  • 2020-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多