天天看點

兩個粒度看Asp.net生命周期

  對于Asp.net頁面層開發無論是寫頁面還是寫控件,我覺得都可以用一句話描述:"Do the right thing at the right time in the right place."這是07年底的一篇東西,還是有點價值整理出來與大家共享。 

    本文從兩個粒度對Asp.net生命周期做了展示,一是通過記錄頁面事件的觸發順序看請求的處理流程,一是通過Reflector看Page類内部對請求處理的實作,為了清晰我清理掉了ETW相關的代碼保留了一個簡化卻足可以說明問題的流程骨架;

    本文覆寫以下内容:

頁面事件的觸發順序展示

清理掉ETW代碼後的,Page類内部對請求處理的實作

MSDN關于Asp.net生命周期非常重要的四個表格

示範源代碼下載下傳

 1

兩個粒度看Asp.net生命周期

using System;

 2

兩個粒度看Asp.net生命周期

using System.Configuration;

 3

兩個粒度看Asp.net生命周期

using System.Data;

 4

兩個粒度看Asp.net生命周期

using System.Web;

 5

兩個粒度看Asp.net生命周期

using System.Web.Security;

 6

兩個粒度看Asp.net生命周期

using System.Web.UI;

 7

兩個粒度看Asp.net生命周期

using System.Web.UI.HtmlControls;

 8

兩個粒度看Asp.net生命周期

using System.Web.UI.WebControls;

 9

兩個粒度看Asp.net生命周期

using System.Web.UI.WebControls.WebParts;

10

兩個粒度看Asp.net生命周期

11

兩個粒度看Asp.net生命周期

public partial class _Default : System.Web.UI.Page

12

兩個粒度看Asp.net生命周期

{

13

兩個粒度看Asp.net生命周期

    protected void Page_PreInit(object sender, EventArgs e)

14

兩個粒度看Asp.net生命周期

    {

15

兩個粒度看Asp.net生命周期

        Response.Write("Page_PreInit<br/>");

16

兩個粒度看Asp.net生命周期

    }

17

兩個粒度看Asp.net生命周期

    protected void Page_Init(object sender, EventArgs e)

18

兩個粒度看Asp.net生命周期

19

兩個粒度看Asp.net生命周期

        Response.Write("Page_Init<br/>");

20

兩個粒度看Asp.net生命周期

21

兩個粒度看Asp.net生命周期

22

兩個粒度看Asp.net生命周期

    protected void Page_InitComplete(object sender, EventArgs e)

23

兩個粒度看Asp.net生命周期

24

兩個粒度看Asp.net生命周期

        Response.Write("Page_InitComplete<br/>");

25

兩個粒度看Asp.net生命周期

26

兩個粒度看Asp.net生命周期

27

兩個粒度看Asp.net生命周期

    protected void Page_PreLoad(object sender, EventArgs e)

28

兩個粒度看Asp.net生命周期

29

兩個粒度看Asp.net生命周期

        Response.Write("Page_PreLoad<br/>");

30

兩個粒度看Asp.net生命周期

31

兩個粒度看Asp.net生命周期

32

兩個粒度看Asp.net生命周期

    protected void Page_Load(object sender, EventArgs e)

33

兩個粒度看Asp.net生命周期

34

兩個粒度看Asp.net生命周期

        Response.Write("Page_Load<br/>");

35

兩個粒度看Asp.net生命周期

36

兩個粒度看Asp.net生命周期

37

兩個粒度看Asp.net生命周期

    protected void Page_LoadComplete(object sender, EventArgs e)

38

兩個粒度看Asp.net生命周期

39

兩個粒度看Asp.net生命周期

        Response.Write("Page_LoadComplete<br/>");

40

兩個粒度看Asp.net生命周期

41

兩個粒度看Asp.net生命周期

42

兩個粒度看Asp.net生命周期

    protected void Page_PreRender(object sender, EventArgs e)

43

兩個粒度看Asp.net生命周期

44

兩個粒度看Asp.net生命周期

        Response.Write("Page_PreRender<br/>");

45

兩個粒度看Asp.net生命周期

46

兩個粒度看Asp.net生命周期

47

兩個粒度看Asp.net生命周期

    protected void Page_SaveStateComplete(object sender, EventArgs e)

48

兩個粒度看Asp.net生命周期

49

兩個粒度看Asp.net生命周期

        Response.Write("Page_SaveStateComplete<br/>");

50

兩個粒度看Asp.net生命周期

51

兩個粒度看Asp.net生命周期

52

兩個粒度看Asp.net生命周期

53

兩個粒度看Asp.net生命周期

54

兩個粒度看Asp.net生命周期

    protected void Page_Unload(object sender, EventArgs e)

55

兩個粒度看Asp.net生命周期

56

兩個粒度看Asp.net生命周期

        int i = 0;

57

兩個粒度看Asp.net生命周期

        i++;//這行代碼是用來設定斷點的,為什麼不用Response.Write?你說呢?

58

兩個粒度看Asp.net生命周期

59

兩個粒度看Asp.net生命周期

60

兩個粒度看Asp.net生命周期

61

兩個粒度看Asp.net生命周期

62

兩個粒度看Asp.net生命周期

    protected void Button1_Click(object sender, EventArgs e)

63

兩個粒度看Asp.net生命周期

64

兩個粒度看Asp.net生命周期

        Label1.Text = "ControlEvent";

65

兩個粒度看Asp.net生命周期

        Response.Write("Button事件觸發!<br/>");

66

兩個粒度看Asp.net生命周期

67

兩個粒度看Asp.net生命周期

}

68

兩個粒度看Asp.net生命周期

69

兩個粒度看Asp.net生命周期

70

兩個粒度看Asp.net生命周期

運作結果:

Page_PreInit

Page_Init

Page_InitComplete

Page_PreLoad

Page_Load

Page_LoadComplete

Page_PreRender

Page_SaveStateComplete

點選頁面的Button後的輸出:

Button事件觸發!

我們從一個更細的粒度,在Reflector中看Page對請求處理的代碼:

  1 private void ProcessRequestMain(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint)

  2 {

  3     try

  4     {

  5         HttpContext context = this.Context;

  6         string str = null;

  7         if (includeStagesBeforeAsyncPoint)

  8         {

  9             if (this.IsInAspCompatMode)

 10             {

 11                 AspCompatApplicationStep.OnPageStartSessionObjects();

 12             }

 13             if (this.PageAdapter != null)

 14             {

 15                 this._requestValueCollection = this.PageAdapter.DeterminePostBackMode();

 16             }

 17             else

 18             {

 19                 this._requestValueCollection = this.DeterminePostBackMode();

 20             }

 21             string callbackControlID = string.Empty;

 22             if (this.DetermineIsExportingWebPart())

 23             {

 24                 if (!RuntimeConfig.GetAppConfig().WebParts.EnableExport)

 25                 {

 26                     throw new InvalidOperationException(SR.GetString("WebPartExportHandler_DisabledExportHandler"));

 27                 }

 28                 str = this.Request.QueryString["webPart"];

 29                 if (string.IsNullOrEmpty(str))

 30                 {

 31                     throw new InvalidOperationException(SR.GetString("WebPartExportHandler_InvalidArgument"));

 32                 }

 33                 if (string.Equals(this.Request.QueryString["scope"], "shared", StringComparison.OrdinalIgnoreCase))

 34                 {

 35                     this._pageFlags.Set(4);

 36                 }

 37                 string str3 = this.Request.QueryString["query"];

 38                 if (str3 == null)

 39                 {

 40                     str3 = string.Empty;

 41                 }

 42                 this.Request.QueryStringText = str3;

 43                 context.Trace.IsEnabled = false;

 44             }

 45             if (this._requestValueCollection != null)

 46             {

 47                 if (this._requestValueCollection["__VIEWSTATEENCRYPTED"] != null)

 48                 {

 49                     this.ContainsEncryptedViewState = true;

 50                 }

 51                 callbackControlID = this._requestValueCollection["__CALLBACKID"];

 52                 if ((callbackControlID != null) && (this._request.HttpVerb == HttpVerb.POST))

 53                 {

 54                     this._isCallback = true;

 55                 }

 56                 else if (!this.IsCrossPagePostBack)

 57                 {

 58                     VirtualPath path = null;

 59                     if (this._requestValueCollection["__PREVIOUSPAGE"] != null)

 60                     {

 61                         try

 62                         {

 63                             path = VirtualPath.CreateNonRelativeAllowNull(DecryptString(this.        _requestValueCollection["__PREVIOUSPAGE"]));

 64                         }

 65                         catch (CryptographicException)

 66                         {

 67                             this._pageFlags[8] = true;

 68                         }

 69                         if ((path != null) && (path != this.Request.CurrentExecutionFilePathObject))

 70                         {

 71                             this._pageFlags[8] = true;

 72                             this._previousPagePath = path;

 73                         }

 74                     }

 75                 }

 76             }

 77             if (this.MaintainScrollPositionOnPostBack)

 78             {

 79                 this.LoadScrollPosition();

 80             }

 81             

 82             this.PerformPreInit();          

 83             

 84             this.InitRecursive(null);

 85             

 86             this.OnInitComplete(EventArgs.Empty);

 87             

 88             if (this.IsPostBack)

 89             {

 90                 this.LoadAllState();

 91             

 92                 this.ProcessPostData(this._requestValueCollection, true);

 93             

 94             }

 95             

 96             

 97             this.OnPreLoad(EventArgs.Empty);

 98             

 99             this.LoadRecursive();

100             

101             if (this.IsPostBack)

102             {

103                 this.ProcessPostData(this._leftoverPostData, false);

104             

105                 this.RaiseChangedEvents();

106              

107                 this.RaisePostBackEvent(this._requestValueCollection);

108              

109             }

110             

111             this.OnLoadComplete(EventArgs.Empty);

112             

113             if (this.IsPostBack && this.IsCallback)

114             {

115                 this.PrepareCallback(callbackControlID);

116             }

117             else if (!this.IsCrossPagePostBack)

118             {

119             

120                 this.PreRenderRecursiveInternal();

121              }

122         }

123         if ((this._asyncInfo == null) || this._asyncInfo.CallerIsBlocking)

124         {

125             this.ExecuteRegisteredAsyncTasks();

126         }

127         if (includeStagesAfterAsyncPoint)

128         {

129             if (this.IsCallback)

130             {

131                 this.RenderCallback();

132             }

133             else if (!this.IsCrossPagePostBack)

134             {

135                 this.PerformPreRenderComplete();

136             

137                 if (context.TraceIsEnabled)

138                 {

139                     this.BuildPageProfileTree(this.EnableViewState);

140                     this.Trace.Write("aspx.page", "Begin SaveState");

141                 }

142             

143                 this.SaveAllState();

144             

145                 this.OnSaveStateComplete(EventArgs.Empty);

146                 if (str != null)

147                 {

148                     this.ExportWebPart(str);

149                 }

150                 else

151                 {

152                     this.RenderControl(this.CreateHtmlTextWriter(this.Response.Output));

153                 }

154             

155                 this.CheckRemainingAsyncTasks(false);

156             }

157         }

158     }

159     catch (ThreadAbortException exception)

160     {

161         HttpApplication.CancelModuleException exceptionState = exception.ExceptionState as HttpApplication.CancelModuleException;

162         if (((!includeStagesBeforeAsyncPoint || !includeStagesAfterAsyncPoint) || ((this._context.Handler != this) || (this._context.ApplicationInstance == null))) || ((exceptionState == null) || exceptionState.Timeout))

163         {

164             this.CheckRemainingAsyncTasks(true);

165             throw;

166         }

167         this._context.ApplicationInstance.CompleteRequest();

168         Thread.ResetAbort();

169     }

170     catch (ConfigurationException)

171     {

172         throw;

173     }

174     catch (Exception exception3)

175     {

176         PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_DURING_REQUEST);

177         PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_TOTAL);

178         if (!this.HandleError(exception3))

179         {

180             throw;

181         }

182     }

183 }

184 

185  

186 

187  

188 

private void PerformPreInit()

           this.OnPreInit(EventArgs.Empty);

    this.InitializeThemes();//看到主題和模闆頁是什麼時候加載了吧

    this.ApplyMasterPage();

    this._preInitWorkComplete = true;

MSDN上對Asp.net生命周期解釋有非常重要的四個表格:

Stage

Description

Page request

The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start

In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.

Page initialization

During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

Load

During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Validation

During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

Postback event handling

If the request is a postback, any event handlers are called.

Rendering

Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.

Unload

Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.

Life-cycle Events

Page Event

Typical Use

PreInit

Use this event for the following:

Check the IsPostBack property to determine whether this is the first time the page is being processed.

Create or re-create dynamic controls.

Set a master page dynamically.

Set the Theme property dynamically.

Read or set profile property values.

Note:

If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

Init

Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.

InitComplete

Raised by the Page object. Use this event for processing tasks that require all initialization be complete.

PreLoad

Use this event if you need to perform processing on your page or control before the Load event.

After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.

Use the OnLoad event method to set properties in controls and establish database connections.

Control events

Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.

In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.

LoadComplete

Use this event for tasks that require that all other controls on the page be loaded.

PreRender

Before this event occurs:

The Page object calls EnsureChildControls for each control and for the page.

The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.

SaveStateComplete

Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.

Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.

Render

This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup that is sent to the browser.

A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.

This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Data Binding Events for Data-Bound Controls

To help you understand the relationship between the page life cycle and data binding events, the following table lists data-related events in data-bound controls such as the GridView, DetailsView, and FormView controls.

Control Event

DataBinding

This event is raised by data-bound controls before the PreRender event of the containing control (or of the Page object) and marks the beginning of binding the control to the data.

Use this event to manually open database connections, if required. (The data source controls often make this unnecessary.)

RowCreated (GridView only) or ItemCreated (DataList, DetailsView, SiteMapPath, DataGrid, FormView, Repeater, and ListView controls)

Use this event to manipulate content that is not dependent on data binding. For example, at run time, you might programmatically add formatting to a header or footer row in a GridView control.

RowDataBound (GridView only) or ItemDataBound (DataList, SiteMapPath, DataGrid, Repeater, and ListView controls)

When this event occurs, data is available in the row or item, so you can format data or set the FilterExpression property on child data source controls for displaying related data within the row or item.

DataBound

This event marks the end of data-binding operations in a data-bound control. In a GridView control, data binding is complete for all rows and any child controls.

Use this event to format data bound content or to initiate data binding in other controls that depend on values from the current control's content. (For details, see "Catch-up Events for Added Controls" earlier in this topic.)

Login Control Events

The Login control can use settings in the Web.config file to manage membership authentication automatically. However, if your application requires you to customize how the control works, or if you want to understand how Login control events relate to the page life cycle, you can use the events listed in the following table.

LoggingIn

This event is raised during a postback, after the page's LoadComplete event has occurred. It marks the beginning of the login process.

Use this event for tasks that must occur prior to beginning the authentication process.

Authenticate

This event is raised after the LoggingIn event.

Use this event to override or enhance the default authentication behavior of a Login control.

LoggedIn

This event is raised after the user name and password have been authenticated.

Use this event to redirect to another page or to dynamically set the text in the control. This event does not occur if there is an error or if authentication fails.

LoginError

This event is raised if authentication was not successful.

Use this event to set text in the control that explains the problem or to direct the user to a different page.

繼續閱讀