Rus*_*ark 11 asp.net-mvc html-encode
我有一个ASP.Net MVC 3页面,其中有一个Html.TextAreaFor控件,请参阅下面的代码.如果我尝试将页面提交到带有尖括号中的文本的http post动作,例如:<test>,我会看到一个黄色错误屏幕:
从客户端检测到潜在危险的Request.Form值(RequestText ="").
我不明白为什么我这样做是因为我发现Scott Guthrie的一篇文章说<%: %>.Net 4中的新语法会自动HtmlEncode元素.因为我正在使用Html.TextAreaFor控件的<%:%>语法,我认为它会自动处理这个并将尖括号转换为正确的"< ;; 和">"字符串.
<% using (Html.BeginForm())
{ %>
<%: Html.ValidationSummary() %>
<h2>Enter a description of the support needed</h2>
<%: Html.TextAreaFor( m => m.RequestText, 4, 90, null) %>
<input type="submit" value="Submit" />
<% } %>
Run Code Online (Sandbox Code Playgroud)
Cha*_*ell 20
基本上,现在,你编码的内容TextAreaFor的输出.由于您正在尝试处理输入,因此这对您没有任何帮助
如果您想提交"有潜在危险"的内容,您需要
1)用RequestTextViewModel 装饰属性[AllowHtml].(优选的)
[AllowHtml]
public string RequestText { get; set; }
Run Code Online (Sandbox Code Playgroud)
2)禁用 validateRequest
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime requestValidationMode="2.0" />
</system.web>
Run Code Online (Sandbox Code Playgroud)
然后,您必须确保在将数据提交到存储库层或数据库之前对控制器中的数据进行适当的清理和/或编码.
您可以RequestText使用以下代码在视图模型上装饰您的属性AllowHtmlAttribute:
[AllowHtml]
public string RequestText { get; set; }
Run Code Online (Sandbox Code Playgroud)
这样,您授权客户端仅为此属性提交HTML.
就<%: %>语法而言,这用于在将某些值输出到页面之前对其进行HTML编码.它用于防止XSS攻击.这与您的情况无关,因为您没有输出到页面,您在请求中接收HTML字符.