编码字符未正确呈现

Encoded characters are not rendering correctly

我正在为 HttpUtility.HtmlEncode 使用 shorthand 对进入我的文本框的数据进行编码。

<asp:TextBox ID="txtProperty" runat="server" Text='<%#: Bind("Property")%>'></asp:TextBox>

我对编码字符行为方式的理解是,当您的网络浏览器呈现它们时,它们应该显示为它们所代表的字符,而不是实际的编码字符。正如 MSDN 网站上的 example code 所暗示的那样。

但是我的编码字符不是这样的。

例如,从数据库中检索到的“£”字符在文本框中显示为:

而不是:

我认为这与我的网站配置处理编码的方式没有任何关系,因为如果我手动将文本设置为 HTML:

中的编码字符
<asp:TextBox ID="txtProperty" runat="server" Text="&#163;"></asp:TextBox>

它将编码的字符正确呈现为:

这表明我使用 HtmlEncode 的方式有问题。

我仍然尝试在我的 webconfig 中将编码显式设置为 UTF-8,但没有任何区别。

有人可以解释这种行为吗,或者这里可能有什么问题?

当您执行 <%#: Bind("Property")%> ASP.NET 时,将已经处理 HTML- 对字符串进行编码,如果您对其进行预编码,您将陷入双重编码情况。

参见 ScottGu 的 New <%: %> Syntax for HTML Encoding Output in ASP.NET 4 (and ASP.NET MVC 2)

ASP.NET 4 introduces a new IHtmlString interface (along with a concrete implementation: HtmlString) that you can implement on types to indicate that its value is already properly encoded (or otherwise examined) for displaying as HTML, and that therefore the value should not be HTML-encoded again.

The <%: %> code-nugget syntax checks for the presence of the IHtmlString interface and will not HTML encode the output of the code expression if its value implements this interface.

This allows developers to avoid having to decide on a per-case basis whether to use <%= %> or <%: %> code-nuggets.

Instead you can always use <%: %> code nuggets, and then have any properties or data-types that are already HTML encoded implement the IHtmlString interface.