.net MVC 设置表单允许提交Html

Asp.net表单验证功能是为了防止http请求中包含恶意内容,如html,js。

当业务需要允许录入此类内容时可以做一下设置:

1.关闭表单的验证([ValidateInput(false)]
[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(string comment) 
{
    if (ModelState.IsValid) 
    {
        //  Etc.
    }
    return View(comment);
}
2.单独设置某个表单属性不做验证([AllowHtml]
class Info{
public int Id {get;set;}
[AllowHtml]
public string Prop1 { get;  set; }
}

[HttpPost]
public ActionResult Edit(Info info) { if (ModelState.IsValid) { // Etc. } return View(comment); }
3.当使用Rquest.Form时(Unvalidated
[HttpPost]
public ActionResult Edit() 
{   
    var rawComment = Request.Unvalidated.Form["comment"];
    
    return View();
}

另外,注意web.config有一处配置为前提

<system.web>
  <httpRuntime requestValidationMode="2.0" />
</system.web>

MSDN参考连接

原文地址:https://www.cnblogs.com/rttc/p/6408543.html