.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>

猜你喜欢

转载自blog.csdn.net/qmdweb/article/details/81459015