ASP.NET 4.5和Visual Studio 2012中的新增功能显示了一个内置的AntiXSS库
<httpRuntime ...
encoderType="System.Web.Security.AntiXss.AntiXssEncoder,System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
@Html.TextBoxFor(x => x.Name, new { @class = "testClass", maxlength = "50" })
它充满电,你会得到
"A potentially dangerous Request.Form value was detected from the client (Name="<b> test </b>").""
对于任何潜在的危险检测,
但是
如果我想要这种保护,但也允许wysiwyg HTML编辑器使用一些HTML内容,我该怎么办?(例如论坛帖子)
正如@NickBork在评论中提到的,这种错误来自ASP.NET请求验证,与AntyXSS库无关。AntiXSS库不会保护您的应用程序免受危险输入的影响。它可以帮助你,但你必须明确使用它。
要跳过某些属性的请求验证,可以使用AllowHtmlAttribute:
// model
public class MyModel
{
[AllowHtml]
public string HtmlContent { get; set; }
}
// controller
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(MyModel myModel)
{
// use myModel.HtmlContent
return View(myModel);
}
}
@* view *@
@model MyModel
<form action="@Url.Action("Index")" method="POST">
@Html.TextBoxFor(m => m.HtmlContent)
<button type="submit">Submit</button>
</form>
@if (Model != null)
{
<div>
@Html.Raw(Model.HtmlContent)
</div>
}