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,仔細檢查代碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章