原因:

    由于在asp.net中,Request提交时出现有html代码或javascript等字符串时,程序系统会认为其具有潜在危险的值。环境配置会报出“从客户端 中检测到有潜在危险的Request.Form值”这样的Error。


解决方法:

方法1:禁用validateRequest

在.aspx文件头中加入这句:

<%@ Page validateRequest="false"  %>

方法2:修改web.config文件

因为validateRequest默认值为true。只要设为false即可:

<configuration>
    <system.web>
        <pages validateRequest="false" />
    </system.web>
</configuration>

备注:如果你是.net 4.0或更高版本,一定要加入如下内容:

web.config里面加上

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

     因为4.0的验证在HTTP的BeginRequest前启用,因此,请求的验证适用于所有ASP.NET资源,aspx页面,ashx页面,Web服务和一些HTTP处理程序等.


方法3(推荐):HtmlEncode, HtmlDecode

    利用Server.HtmlEncode(string)方法,对字符串进行编码,这样就会将危险字符转义为普通的字符。如TextBox1.Text=Server.HtmlEncode(str);


    protected void Page_Load(object sender, EventArgs e)
    {	// This could mess up HTML.
	string text = "you & me > them"; // 1

	// Replace > with >
	string htmlEncoded = Server.HtmlEncode(text); // 2

	// Now has the > again.
	string original = Server.HtmlDecode(htmlEncoded); // 3

	// This is how you can access the Server in any class.
	string alsoEncoded = HttpContext.Current.Server.HtmlEncode(text); // 4

	StringWriter stringWriter = new StringWriter();
	using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
	{	    // Write a DIV with encoded text.
	    writer.RenderBeginTag(HtmlTextWriterTag.Div);
	    writer.WriteEncodedText(text);
	    writer.RenderEndTag();
	}
	string html = stringWriter.ToString(); // 5
    }

输出:

Step 1: Before encoding has occurred.String: you & me > them

Step 2: The string is encoded for HTML.String: you &amp; me &gt; them

Step 3: String is converted back from HTML.String: you & me > them

Step 4: The string is encoded for HTML again.String: you &amp; me &gt; them

Step 5: The HTML string is written into a DIV.Text:   <div>you &amp; me &gt; them</div>