AllowHtml不起作用

我正在构建一个内容管理系统,允许我以外的人更新网站上的内容。

我有一个面向前面的HTML表单,通过AJAX将数据发送到控制器:

// CONTROLLER [ValidateInput(false)] public void CarAJAX() { CarAdmin CA = new CarAdmin(); CA.UpdateCar(System.Web.HttpContext.Current.Request); } 

这些数据将包含HTML,因此我的模型中出现错误:

 // MODEL using System; using System.Web; using System.Web.Mvc; namespace Site.Models { public class CarAdmin { public String id { get; set; } [AllowHtml] public String HTML_Stuff { get; set; } public CarAdmin(){} public void UpdateCar(HttpRequest Request) { HTML_Stuff = Request.Form["HTML_Stuff"]; // <-- ERROR HAPPENS HERE!!!!!! // sanitation and validation String Select = String.Format("UPDATE Car Set HTML_Stuff = {0} WHERE id = {1}", HTML_Stuff, id); // Execute DB Command } } } 

如代码所示,当我尝试将成员设置为等于具有HTML的请求变量时,我收到错误。

编辑:错误是’检测到潜在危险的Request.Form值’

这是我尝试过的:

  • 更改web.config中的validation模式 ,但是当只有一个变量具有HTML时,我不想更改整个站点的validation。

  • 模型中的[AllowHtml] ,但我仍然得到相同的错误 – 好像[AllowHtml]什么也没做。

  • Controller中的[ValidateInput(false)] ,类似于AllowHtml ,似乎没有任何影响。

我在这里错过了什么吗?

我有同样的问题。 “requestValidationMode =”2.0“”在web.config中设置, [AllowHtml]也设置在适当的属性上,我仍然收到错误“检测到潜在危险的Request.Form值…”。

但我观察到控制器方法实际上被调用(我能够调试方法)所以这必须意味着validation实际上已关闭。 在调用堆栈中,我注意到反复出现类似于“System.Web.Caching.OutputCacheModule”的缓存类,这让我想到这我在整个控制器上关闭的缓存有关,就像这样“ [OutputCache( NoStore = true,持续时间= 0)]“

基于此,我尝试将缓存的位置设置为OutputCacheLocation.None,这就行了。 所以我最终使用[OutputCache(NoStore = true,Duration = 0,Location = OutputCacheLocation.None)] 工作,最后没有validation,也没有使我的请求失败

试试这个:

 // CONTROLLER [HttpPost] public ActionResult CarAJAX(CarAdmin model) { model.UpdateCar(); } // MODEL using System; using System.Web; using System.Web.Mvc; namespace Site.Models { public class CarAdmin { private string html; public String id { get; set; } [AllowHtml] public String HTML_Stuff { get { return html; } set { // sanitation and validation on "value" html = value; } } public CarAdmin(){} public void UpdateCar() { String Select = String.Format("UPDATE Car Set HTML_Stuff = {0} WHERE id = {1}", HTML_Stuff, id); // Execute DB Command } } } 

我还注意到你正在validation方法内部。 如果你在设置属性时这样做可能会更好。

编辑:
我对这个话题进行了很多研究。 您实际上需要使用AJAX将模型绑定到控制器。 请看这个例子 。 我不确定你的代码范围,但我认为你还需要ActionResult在控制器内返回。 从ActionResult返回的内容有很好的例子。

你应该这样做 –

创建一个单独的类,其中包含所需的实体 –

 public class EntityDto { public String id { get; set; } [AllowHtml] public String HTML_Stuff { get; set; } } 

然后在你的控制器方法中使用它 –

 [ValidateInput(false)] public void UpdateCar(EntityDto model) { var html_stuff = model.HTML_Stuff; // sanitation and validation String Select = String.Format("UPDATE Car Set HTML_Stuff = {0} WHERE id = {1}", html_stuff , id); // Execute DB Command } 

如果有帮助,请告诉我。