ASP.NET Postback回调后参数无效

描述 

ASP.net 添加了"event validation"的功能, ASP.NET会检查 POST方法中的所带的参数,如果认为不合法,就会抛出异常,信息如下:

Invalid postback or callback argument. 
        Event validation is enabled using <pages enableEventValidation="true"/> in 
    configuration or <%@ Page EnableEventValidation="true" %> in a page. 
        For security purposes, this feature verifies that arguments to postback or 
    callback events originate from the server control that originally rendered them. 
        If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation 
    method in order to register the postback or callback data for validation. 


这个设计的目的是为了防止恶意用户利用post 方法发送一些恶意数据.但是有时一些常见的case也会出错,比如使用客户端脚本,根据页面上的其他控件的内容来改变一个dropdown list的内容,最常见的case就是省市县3级联动菜单.又比如在页面上添加一个dropdown list,然后给它添加3个item,再使用客户端脚本在dropdown list中添加一个item,如果dropdown list的AutoPostBack="True",每次选择list item都会引起postback, 如果所选的item为dropdown list本来就有的,一切正常.如果所选的item是通过客户端脚本添加的,就会出现异常.在asp.net render DropDownList 时,会遍历DropDownList的item,并记录所有可能的postback的值,其算法为
hash(DropDownList’s UniqueID XOR hash(ListItem’s Value property)),计算的结果会被保存在page中,

<input type="hidden" 
       name="__EVENTVALIDATION" 
       id="__EVENTVALIDATION"
       value="/wEWBQKGg9abDQKd9sHMBgKc9s…….." 
/>


这个过程发生在control的Render()方法中当页面postback时,ASP.NET会根据这个隐藏值检查postback values,如果找不到对应信息,就会报错

解决方法

1. 禁止这个功能, 但同时会失去一些安全保障:

//—-通过web.config
<system.web>
   <pages enableEventValidation="false"/>
</system.web>
//—-针对某个page
<%@ Page EnableEventValidation="false" … %>


2. Register For Event Validation,其原理就是让asp.net记录这个postback value.RegisterForEventValidation必须在render时调用:

protected override void Render(HtmlTextWriter writer)
{
   ClientScript.RegisterForEventValidation(_recipeList.UniqueID,"4");
   base.Render(writer);
}

如果我们自己写了一个control,需要使用validate events功能,就需要使用SupportsEventValidation attribute,

[SupportsEventValidation]
public class DynamicDropDownList : DropDownList
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
     Page.ClientScript.RegisterForEventValidation(this.UniqueID, "4");
     base.Render(writer);
}
}


3. Form嵌套,一个页面只能有一个Form,仔细检查代码。

原文地址:https://www.cnblogs.com/hainange/p/6153586.html