"潜在危险的Request.Form值"

Mic*_*elS 2 c# asp.net asp.net-mvc asp.net-mvc-3

我收到了错误

从客户端检测到潜在危险的Request.Form值

当我部署我的应用程序时(当我通过localhost运行时不会发生错误).

它在提交表单时发生,因为其中一个字段包含HTML.我在模型中的属性周围添加了[AllowHtml],对应于有问题的表单字段,但这似乎不起作用.

我不想在动作方法上使用[ValidateInput(false)],原因显而易见,无论如何,这似乎也不起作用.

我还需要做其他任何配置吗?我已经读到了添加

<httpRuntime requestValidationMode="2.0"/>
Run Code Online (Sandbox Code Playgroud)

到Web配置文件可以解决它,但我再次不想添加,因为我仍然想要我的应用程序的其他部分的安全验证.

有任何想法吗?

Dar*_*rov 8

[AllowHtml]要求你添加<httpRuntime requestValidationMode="2.0"/>(设置这个值并不意味着你没有获得安全验证,它只是验证模式).网站的其他部分将是安全的,您只能对视图模型上的特定属性禁用验证.

[ValidateInput(false)] 会工作,但正如你所说,它可能不太安全,因为它禁用所有属性的验证.

我会坚持[AllowHtml].


更新:

双方[AllowHtml][ValidateInput(false)]在ASP.NET MVC 3开箱的无添加的要求,<httpRuntime requestValidationMode="2.0"/>在web.config中.这在ASP.NET 4.0下运行的ASP.NET MVC 2中是必需的

这是一个例子:

查看型号:

public class MyViewModel
{
    [AllowHtml]
    public string Text { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Text = "<html/>"
        };

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}
Run Code Online (Sandbox Code Playgroud)

视图:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.TextAreaFor(x => x.Text)
    <input type="submit" value="OK" />
}
Run Code Online (Sandbox Code Playgroud)

提交表单时不会抛出异常.