如果你看一下反XSS库,他们通常会对HTML内容和HTML属性进行不同的编码。例如,使用Microsoft's WPL implementation:
<@ Imports Namespace="Microsoft.Security.Application" %>
<span attribute="<%= AntiXss.HtmlAttributeEncode(attrVariable) %>">
<%= AntiXss.HtmlEncode(contentVariable) %>
</span>
现在,ASP.Net已经添加了编码蜂鸣器,使这更容易:
<span attribute="<%: attrVariable %>">
<%: contentVariable %>
</span>
然后您可以specify the encoder to use in the web.config:
<system.web>
<httpRuntime encoderType="AntiXssEncoder, AssemblyName"/>
此处的编码器知道是否根据上下文调用HtmlAttributeEncode
或HtmlEncode
。
我的问题是我有一个实现IHtmlString
的智能类 - 这告诉<%:
语法完全绕过它。但是我仍然希望根据上下文进行不同的编码:
<% var item = GetImplementationOfIHtmlString() %>
<span attribute="<%: item %>"> <!-- attribute encodes -->
<%: item %> <!-- HTML encodes -->
</span>
IHtmlString.ToHtmlString
是否有办法了解上下文(HTML内容的编码或属性内部的编码)?
答案 0 :(得分:1)
没有。自定义HtmlEncode方法的合同是它们也必须适合于属性编码(当属性值被引号括起时)。这样&lt;%:%&gt;语法不需要上下文意识。