ASP MVC 4.5 AntiXSS Library +允许HTML内容

时间:2013-07-30 20:13:33

标签: asp.net-mvc-4 antixsslibrary

What's New in ASP.NET 4.5 and 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内容,我该怎么办? (例如论坛帖子)

1 个答案:

答案 0 :(得分:3)

正如@NickBork在他的comment中提到的,这种错误来自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>
}