1 IsPostBack介紹
IsPostBack是Page類有一個bool類型的屬性,用來判斷針對目前Form的請求是第一次還是非第一次請求。當IsPostBack=true時表示非第一次請求,我們稱為PostBack,當IsPostBack=false時表示第一次請求。在asp.net架構内部有很多的場景需要判斷IsPostBack,比如LoadAllState等操作就需要在PostBack的時候進行。對于我們自己使用WebForm進行開發時,經常會在Page_Load中對IsPostBack進行判斷,因為第一次請求的時候會執行Page_Load,在非第一次請求的時候也會執行Page_Load。為什麼對同一個Form有多次請求呢?asp.net中引入了伺服器端事件,支援伺服器端事件的控件,會發出對目前Form的請求,這樣在很多情形下我們就需要差別是否是對這個Form的第一次請求。
2 IsPostBack結論
本人對.Net的源代碼中相關的處理進行的分析得到如下的結論:
結論① 對于使用Server.Transfer進行遷移時遷移到的頁面其IsPostBack=false。
結論② Post方式如果Request中沒有請求值,即Request.Form =null則IsPostBack=false;Get方式如果Request中沒有請求值,即Request.QueryString =null則IsPostBack=false。
結論③ 如果QueryString或Form雖然有請求值,但是QueryString或Form中的Key沒有“__VIEWSTATE”和“__EVENTTARGET”和“__VIEWSTATEFIELDCOUNT”,并且沒有鍵為“null”,值以“__VIEWSTATE”開頭并且也沒有值為“__EVENTTARGET”的鍵值對,則IsPostBack=false。
結論④ 使用Response.Redirect方式向自畫面遷移時,此時IsPostBack=false。
結論⑤ 發生跨頁送出(CrossPagePostBack),當通路PreviousPage屬性的時候,對于源Page,IsPostBack=true。
結論⑥ 發生跨頁送出(CrossPagePostBack)時目标頁面是IsPostBack=false
結論⑦ 使用Server.Execute遷移到的頁面其IsPostBack=false。
結論⑧ 在Page運作期間其對應的DLL被更新了并且Page的樹結構發生過變化,這種情況下請求時IsPostBack=false。
可以這樣來了解這些結論:一般情況判斷Request中如果沒有請求值則IsPostBack=false。如果有請求值但是不包括“__VIEWSTATE”等一些特殊的鍵或值,則IsPostBack=false(每次請求後.Net架構會将一些特殊的隐藏域“__VIEWSTATE”等傳回給用戶端)。還有一些特殊的情形是上面的規則不能正确判斷的需要特殊處理的,這些情形包括Server.Transfer,Response.Redirect,CrossPagePostBack,Server.Execute,發生了頁面元素變化及重新編譯。
一般來說記住上面的結論就可以,如果您有興趣,或者懷疑請繼續看下面的IsPostBack推論過程。
3 IsPostBack推論過程
下面是根據.Net架構中的源代碼,來分析IsPostBack是如何判斷出來的。對于這些結論的推斷本人做了相關的試驗來證明推論的正确性,由于篇幅的原因沒有将這些試驗代碼展現出來。另外不可能将全部的.Net架構的代碼都展現出來,隻是将相關的代碼片段列出,說明推斷的依據。另外由于本人水準有限對.Net架構的代碼了解還存在的不足的地方,請發現後進行指正,謝謝。
publicbool IsPostBack
{
get
{
if (this._requestValueCollection == null)
{
return false;
}
if (this._isCrossPagePostBack)
return true;
if (this_pageFlags[8])
return (
(
(this.Context.ServerExecuteDepth <= 0) ||
((this.Context.Handler != null) &&
(base.GetType() == this.Context.Handler.GetType()))
) && !this._fPageLayoutChanged
);
}
}
我們将每一個if判斷作為一個小節,作如下的分析。
3.1 this._requestValueCollection == null
if (this._requestValueCollection == null)
可以看出_requestValueCollection等于null時IsPostBack就等于false。
在Page.ProcessRequestMain(bool, bool)中有如下的代碼:
if (this.PageAdapter != null)
this._requestValueCollection = this.PageAdapter.DeterminePostBackMode();
else
this._requestValueCollection = this.DeterminePostBackMode();
PageAdapter.DeterminePostBackMode最終還是調用了Page.DeterminePostBackMode,下面我們看Page.DeterminePostBackMode如何實作。
protected internal virtual NameValueCollection DeterminePostBackMode()
if (this.Context.Request == null)
return null;
if (this.Context.PreventPostback)
NameValueCollection collectionBasedOnMethod = this.GetCollectionBasedOnMethod(false);
if (collectionBasedOnMethod == null)
bool flag = false;
string[] values = collectionBasedOnMethod.GetValues((string) null);
if (values != null)
int length = values.Length;
for (int i = 0; i < length; i++)
if (values[i].StartsWith("__VIEWSTATE", StringComparison.Ordinal) ||
(values[i] == "__EVENTTARGET"))
{
flag = true;
break;
}
if (((collectionBasedOnMethod["__VIEWSTATE"] == null) && (collectionBasedOnMethod["__VIEWSTATEFIELDCOUNT"] == null)) && ((collectionBasedOnMethod["__EVENTTARGET"] == null) && !flag))
if (this.Request.QueryStringText.IndexOf(
HttpResponse.RedirectQueryStringAssignment, StringComparison.Ordinal) != -1)
collectionBasedOnMethod = null;
return collectionBasedOnMethod;
這個函數中傳回null就意味者IsPostBack=false,将上面函數中每個傳回為null的地方作如下的分析。
3.1.1 this.Context.Request == null
this.Context.Request == null應該隻有在異常的情況下會發生,正常情況下會在HttpRuntime.ProcessRequestInternal中建立HttpContext及HttpRequest對象。
3.1.2 this.Context.PreventPostback
在HttpServerUtility.Transfer中會使用PreventPostback,其代碼如下:
public void Transfer(string path)
bool preventPostback = this._context.PreventPostback;
this._context.PreventPostback = true;
this.Transfer(path, true);
this._context.PreventPostback = preventPostback;
在調用Server.Transfer進行畫面遷移時設定Context.PreventPostback=ture。此處得出結論①:對于使用Server.Transfer進行遷移時遷移到的頁面其IsPostBack=false。
3.1.3 collectionBasedOnMethod == null
}
調用了Page.GetCollectionBasedOnMethod後其傳回值進行判斷。如果其傳回值為null則IsPostBack為false。Page.GetCollectionBasedOnMethod的定義如下:
internal NameValueCollection GetCollectionBasedOnMethod(bool dontReturnNull)
if (this._request.HttpVerb == HttpVerb.POST)
if (!dontReturnNull && !this._request.HasForm)
{
return null;
}
return this._request.Form;
if (!dontReturnNull && !this._request.HasQueryString)
return null;
return this._request.QueryString;
從上面的代碼可以看出傳回值為null的情形是_request.HasForm=null或_request.HasQueryString=null。此處得出結論②:Post方式如果Request中沒有請求值,即Request.Form =null則IsPostBack=false;Get方式如果Request中沒有請求值,即Request.QueryString =null則IsPostBack=false。
3.1.4 ((collectionBasedOnMethod["__VIEWSTATE"] == null) && (collectionBasedOnMethod["__VIEWSTATEFIELDCOUNT"] == null)) && ((collectionBasedOnMethod["__EVENTTARGET"] == null) && !flag)
int length = values.Length;
上面這段代碼的意思是判斷請求的鍵值對中是否存在沒有鍵,其值以“__VIEWSTATE”開頭或者其值為“__EVENTTARGET”。例如如下的Get請求方式會使得flag=true。
…/defalt.aspx?__VIEWSTATE
…/defalt.aspx?__EVENTTARGET
對于Get方式“?__VIEWSTATE=”會将__VIEWSTATE作為請求的鍵,其值為“”,但是“?__VIEWSTATE”會認為其鍵為“null”,其值為“__VIEWSTATE”
if (
((collectionBasedOnMethod["__VIEWSTATE"] == null) && (collectionBasedOnMethod["__VIEWSTATEFIELDCOUNT"] == null)) && ((collectionBasedOnMethod["__EVENTTARGET"] == null) && !flag))
return null;
如上的條件意味着請求的鍵中同時沒有“__VIEWSTATE”,“__EVENTTARGET”,“__VIEWSTATEFIELDCOUNT”,并且flag為false則傳回null。flag為false意味着沒有鍵為“null”值以“__VIEWSTATE”開頭并且也沒有值為“__EVENTTARGET”的鍵值對。
此處得出結論③如果QueryString或Form雖然有請求值,但是QueryString或Form中的Key沒有“__VIEWSTATE”和“__EVENTTARGET”和“__VIEWSTATEFIELDCOUNT”,并且沒有鍵為“null”值以“__VIEWSTATE”開頭并且也沒有值為“__EVENTTARGET”的鍵值對,則IsPostBack=false。
3.1.5 this.Request.QueryStringText.IndexOf(HttpResponse.RedirectQueryStringAssignment, StringComparison.Ordinal) != -1
if (this.Request.QueryStringText.IndexOf(HttpResponse.RedirectQueryStringAssignment,StringComparison.Ordinal) != -1)
collectionBasedOnMethod = null;
HttpResponse.RedirectQueryStringAssignment的值為“__redir=1”,上面的代碼的意思是如果QueryStringText中包括包括“__redir=1”則傳回null。在HttpRequest.Redirect中會判斷如果IsPostBack為true,并且URL中不包含有“__redir=1”時,會給URL中增加“__redir=1”。一般情況下我們使用request.Redirect遷移到的頁面都應該是IsPostBack=false,有一種特殊的情形是使用request.Redirect遷移到目前頁,此時IsPostBack為true。此種情況發生時在request.Redirect中給URL中增加“__redir=1”。執行到page. ProcessRequestMain時會重新将IsPostBack判斷為fales。
此處得出結論④使用Response.Redirect方式向自畫面遷移時,此時IsPostBack=false。
此時大家可能會有疑問為什麼使用Response.Redirect方式向自畫面遷移時要特殊處理,使用Response.Redirect向其他畫面遷移為什麼不要。使用Response.Redirect向其他畫面遷移時Response.Form=null,Response.QueryString=null,是以可以判斷是IsPostBack=false。但是使用Response.Redirect方式向自畫面遷移時Response.QueryString<>null,是以要特殊判斷。
3.2 this._isCrossPagePostBack
在Page的PreviousPage屬性中會對_isCrossPagePostBack進行設定,具體代碼如下:
public Page PreviousPage
…
ITypedWebObjectFactory vPathBuildResult = (ITypedWebObjectFactory)BuildManager.GetVPathBuildResult(this.Context, this._previousPagePath);
if (typeof(Page).IsAssignableFrom(vPathBuildResult.InstantiatedType))
this._previousPage = (Page) vPathBuildResult.CreateInstance();
this._previousPage._isCrossPagePostBack = true;
this.Server.Execute(this._previousPage, TextWriter.Null, true, false);
return this._previousPage;
在發生跨頁面送出的時候,當通路PreviousPage屬性的時候源Page的IsCrossPagePostBack會被設定true。此處得出結論⑤發生跨頁送出(CrossPagePostBack),當通路PreviousPage屬性的時候,對于源Page,IsPostBack=true。
3.3 this._pageFlags[8]
if (this._pageFlags[8])
在Page. ProcessRequestMain中有如下的代碼片斷對_pageFlags[8]進行指派。
else if (!this.IsCrossPagePostBack)
VirtualPath path = null;
if (this._requestValueCollection["__PREVIOUSPAGE"] != null)
try
path = VirtualPath.CreateNonRelativeAllowNull(
DecryptString(this._requestValueCollection["__PREVIOUSPAGE"]));
catch (CryptographicException)
this._pageFlags[8] = true;
if ((path != null) && (path != this.Request.CurrentExecutionFilePathObject))
this._previousPagePath = path;
解密發生異常時_pageFlags[8]為true這種異常發生的可能性比較小我們忽略,重點看另外一種情形,将這種情形的所有條件結合起來就是IsCrossPagePostBack=false && _requestValueCollection["__PREVIOUSPAGE"] != null && path != null && (path != this.Request.CurrentExecutionFilePathObject)。發生跨頁送出時對于目标頁面IsCrossPagePostBack=false,此時源頁面的"__PREVIOUSPAGE"等資訊會送出給目标頁面,是以_requestValueCollection["__PREVIOUSPAGE"] != null。此時目前請求的CurrentExecutionFilePathObject是根據目标頁的路徑生成的,與使用_requestValueCollection["__PREVIOUSPAGE"]生成的path對象不同。
此處得出結論⑥發生跨頁送出(CrossPagePostBack)時目标頁面是IsPostBack=false。為什麼需要對CrossPagePostBack的目标頁面做這樣的處理呢?發生CrossPagePostBack時,會将源頁面的資訊送出給目标頁面此時Request.Form!=null,而且包括__VIEWSTATE等鍵按照其他的規則會判斷為IsPostBack=true,是以需要對CrossPagePostBack的目标頁面做特殊的判斷。
3.4 (this.Context.ServerExecuteDepth <= 0) || ((this.Context.Handler != null) && (base.GetType() == this.Context.Handler.GetType()))
在HttpServerUtility中有如下的代碼對Context. ServerExecuteDepth進行了操作。
public void Execute(string path, TextWriter writer, bool preserveForm)
…
try
this._context.ServerExecuteDepth++;
handler = this._context.ApplicationInstance.MapHttpHandler(this._context, request.RequestType, path3, filename, useAppConfig);
finally
this._context.ServerExecuteDepth--;
在HttpServerUtility.ExecuteInternal中也有一處對Context.ServerExecuteDepth類似的操作。HttpServerUtility.Execute會調用HttpServerUtility.ExecuteInternal。從此可以看出Context.ServerExecuteDepth是表示Server.Execute中的執行深度。在調用Server.Execute時Context.ServerExecuteDepth>0。另外調用Server.Execute後Context.Handle中存儲的還是原來的頁對象,也就是說base.GetType()!= this.Context.Handler.GetType()。這樣對于Server.Execute來說this.Context.ServerExecuteDepth <= 0) || ((this.Context.Handler != null)這個條件為false。此處得出結論⑦使用Server.Execute遷移到的頁面其IsPostBack=false。此處我們會有疑問,為什麼需要對Server.Execute進行特殊的判斷呢?理由是使用Server.Execute時會将源Page中的隐含域送出,此時Request.Form!=null,而且包括__VIEWSTATE等鍵按照其他的規則會判斷為IsPostBack=true。
3.5 this._fPageLayoutChanged
fPageLayoutChanged從這個變量的字面意思來看是Page的Layout發生了變化。
在Page.LaodAllState中代碼片斷如下:
private void LoadAllState()
string s = (string) second.First;
int num = int.Parse(s, NumberFormatInfo.InvariantInfo);
this._fPageLayoutChanged = num != this.GetTypeHashCode();
其意思是現在得到的HashCode和存儲在ViewState中的HashCode不一緻時fPageLayoutChanged=true。GetTypeHashCode()會傳回一個HashCode,而且這個方法是對aspx進行編譯的時候産生的,隻有在頁面上的元素發生了變化的時候其傳回的值會發生變化。此處得出結論⑧在Page運作期間其對應的DLL被更新了并且Page的樹結構發生過變化,這種情況下請求時IsPostBack=false。
本文轉自94cool部落格園部落格,原文連結:http://www.cnblogs.com/94cool/articles/1532608.html,如需轉載請自行聯系原作者