ASP.Net MVC 3上的HtmlEncode Html.TextAreaFor

HtmlEncode on Post for ASP.Net MVC 3 Html.TextAreaFor

我有一个ASP.Net MVC 3页面,其中有一个Html.TextAreaFor控件,请参见下面的代码。 如果我尝试将页面提交到http post操作中,并在尖括号中添加文本,如,则会显示黄色错误屏幕,提示:

A potentially dangerous Request.Form value was detected from the
client (RequestText="").

我不明白为什么要得到这个,因为我发现了Scott Guthrie的一篇文章,说.Net 4中的新<%: %>语法将自动对元素进行HtmlEncode。 由于我对Html.TextAreaFor控件使用<%:%>语法,因此我认为它将自动处理此问题并将尖括号转换为适当的"&lt;"。 和"&gt"字符串。

1
2
3
4
5
6
7
<% using (Html.BeginForm())
   { %>
    <%: Html.ValidationSummary() %>
    Enter a description of the support needed
    <%: Html.TextAreaFor( m => m.RequestText, 4, 90, null) %>
    <input type="submit" value="Submit" />
<% } %>


基本上现在,您正在对输出中TextAreaFor的内容进行编码。这对您没有任何帮助,因为您正在尝试处理输入

如果您要提交"潜在危险"的内容,则需要

1)用[AllowHtml]装饰ViewModel中的RequestText属性。 (首选)

1
2
[AllowHtml]
public string RequestText { get; set; }

2)禁用validateRequest

1
2
3
4
<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime requestValidationMode="2.0" />
</system.web>

然后,在将数据提交到存储层或数据库之前,必须确保已适当清理该数据和/或在控制器中对其进行编码。


您可以使用AllowHtmlAttribute装饰视图模型上的RequestText属性:

1
2
[AllowHtml]
public string RequestText { get; set; }

这样,您将授权客户端仅为此属性提交HTML。

<%: %>语法而言,此语法用于在将某些值输出到页面之前对其进行HTML编码。它用于防止XSS攻击。这与您的情况无关,因为您没有输出到页面,而是在请求中接收HTML字符。