MVC 请求参数中带有HTML会引发Validation异常 ("A potentially dangerous Request.Form value was detected from the client")

MVC中客户端传值到服务器端时,如果客户端字符串含有“</>"字样时就会报“检测到有潜在危险”(

"A potentially dangerous Request.Form value was detected from the client")的错误。

如:从客户端("test<br/>ttt")中检测到有潜在危险的 Request.Form 值。


解决方法A: 

在对应的Action加上[ValidateInput(false)]属性就可以解决,去除验证。

但似乎在.NET 4.0这个属性不工作,所以在web.config中systerm.web节点中加入

<httpRuntime requestValidationMode="2.0"/> 


解决方法B: 

 方法A还是稍显麻烦,在MVC3中有更好的解决办法,代码如下:

            NameValueCollection paramColl = null;
            // comment strings are html strings, so get the unvalidate version here
            if (0 == String.Compare(request.HttpMethod, "POST", true))
            {
                paramColl = new FormCollection(request.Unvalidated().Form);
            }
            else if (0 == String.Compare(request.HttpMethod, "GET", true))
            {
                paramColl = new NameValueCollection(request.Unvalidated().QueryString);
            }
            else
            {
                paramColl = request.Params;

            } 

原文地址:https://www.cnblogs.com/dlbrant/p/2327797.html