ASP.NET 生命週期(原文翻譯)

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   color   os   ar   使用   

在網上看到這篇文章,老外寫的,裡面很多圖片挺精緻,順帶翻譯過來給大家分享下,英語太次好多地方都翻不過來

 

ASP.NET application and page life cycle

Download source code - 4.03 KB

目錄

 

  • 簡介
  • 兩步處理法
  • 建立ASP.NET環境
  • 使用MHPM事件處理請求
  • 在哪些事件裡我們哪些事?
  • 一個簡單的示範代碼
  • 放大ASP.NET頁面事件
  • 關於源碼
  • references

 

簡介

在這篇文章,我們將努力弄明白從使用者發送請求開始到瀏覽器渲染完畢過程中所發生的不同事件。所以我們要搞清楚ASP.NET請求的兩個大階段,

然後我們來將進入從不同事件來觸發‘HttpHandler’, ‘HttpModule’和ASP.NET頁面對象。在這個事件旅程中,我們要理解每一個事件所發生邏輯過程

這個電子書適合涵蓋.NET中的比如WCF,WPF,WWF,ajax,Core.NET,SQL等等知識點,你可以下載相同的內容from here 或者你可以追我每天的免費課程from here.

兩步處理法

從30000英尺的高度來看(From 30,000 feet level,搞不清作者是不是在戲謔), ASP.NET 請求處理分兩步進行,如下,使用者發送一個請求到IIS:

  • ASP.NET建立一個可以處理該請求的環境,換句話說,它建立了應用程式物件,請求、形影和內容物件來處理改請求
  • 當環境建立完畢,該請求被一系列經過一系列來自於使用模組(by using modules),處理器(handlers)和頁面對象的事件進行處理,為了簡化,我們把這一階段命名為MHPM(Module,Handler,page and Module event),我們一會講詳細介紹

In the coming sections, we will understand both these main steps in more detail.

建立ASP.NET環境

Step 1: 使用者發送了一個請求到IIS,IIS(進程inetinfo.exe)首先檢查哪一個ISAPI可以處理這個請求。這個是由檔案的副檔名來確定的,例如,如果頁面是.aspx的頁面,那麼就會通過‘aspnet_isapi.dll’ 來處理

Step 2: 假如這是對這個網站發送的第一個請求,那麼一個名字叫‘ApplicationManager’的類會建立一個應用程式定義域在網站啟動並執行地方。眾所周知,來自不同網站程式的應用程式定義域是在同一個IIS中是相互隔離的。所以如果在一個app域中存在問題,它是不會影響到其他的app域的。

Step 3: 新建立的app域建立託管環境(hosting environment),例如,‘HttpRuntime’對象。一旦託管環境被建立,那些必須的核心ASP.NET對象比如‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’也會被建立.

Step 4: 一旦所有的ASP.NET核心對象被建立完畢,‘HttpApplication’對象被建立來服務使用者的請求,如果你的系統中包含有一個‘global.asax’檔案,那麼‘global.asax’檔案的對象會被建立。請記住global.asax檔案時內建在‘HttpApplication’類中的。

Note: 第一次一個ASP.NET頁面串連到一個app,一個新的‘HttpApplication’執行個體被建立,為了最大限度提高效能,‘HttpApplication’的執行個體可以重複用於多個請求

Step 5: 然後HttpApplication對象被分配到ASP.NET核心對象來處理頁面.

Step 6: HttpApplication 然後通過HTTP模組事件,處理器和頁面事件來處理請求。它會觸發MHPM事件來進行請求處理

Note: 想瞭解過多, read this.

下面的圖片說明了那些內部對象模組和ASP.NET請求的關係,在最頂層是建立‘Appdomain’的ASP.NET運行時,

Appdomain’包含‘request’, ‘response’ and ‘context’ 對象的‘HttpRuntime

使用MHPM事件處理請求

一旦‘HttpApplication’建立完畢,它開始處理請求了。它經曆了三個不同的階段.它在通過這些階段,它調用不同的事件,在這些事件中,開發人員可以擴充代碼添加自己的邏輯到裡面。

在我們繼續之前,讓我們搞清楚什麼是‘HttpModule’ 和 ‘HttpHandlers’。他們協助我們注入自訂邏輯在ASP.NET頁面處理之前和之後,二者的主要區別如下:

· If you want to inject logic based in file extensions like ‘.ASPX’, ‘.HTML’, then you use ‘HttpHandler’. In other words, ‘HttpHandler’ is an extension based processor.

· If you want to inject logic in the events of ASP.NET pipleline, then you use ‘HttpModule’. ASP.NET. In other words, ‘HttpModule’ is an event based processor.

如果想瞭解更多,戳 here.
下面是請求處理的邏輯過程,下面展示了4個重要步驟:
Step 1(M: HttpModule): 客戶請求處理開始,在ASP.NET引擎運行和建立前,ASP.NET HttpModule 提供可以注入自訂邏輯的事件,它提供了6個重要的事件你可以用在頁面對象建立BeginRequest, AuthenticateRequest,AuthorizeRequest, ResolveRequestCache, AcquireRequestStatePreRequestHandlerExecute之前。


Step 2 (H: ‘HttpHandler’): 當上面6個事件執行完畢,ASP.NET引擎接著觸發事件,假如你的項目中有執行HttpHandler ,ASP.NET引擎將會調用ProcessRequest事件。

Step 3 (P: ASP.NET page):HttpHandler 的邏輯執行,當前ASP.NET頁面對象就建立完畢。當ASP.NET頁面對象建立完,

一些事件被觸發,我們可以在這些頁面事件裡編寫自訂的邏輯,在ASP.NET裡提供6個重要的事件我們可以編寫自訂的邏輯。

頁面的Init, Load, validate, event, render and unload.你可以用單詞SILVER 來記憶這些事件,S-開始(在這個單詞中沒有特殊的含義),I-Init,L-Load,V-Validate,E-Event,R-Render


Step4 (M: HttpModule): 當頁面對象執行完畢並從記憶體中卸載,HttpModule 提供了後期頁面處理事件我們可以用來處理頁面邏輯。

它有4個重要的後期處理事件, PostRequestHandlerExecute, ReleaserequestState, UpdateRequestCacheEndRequest.

下面的圖片詮釋了剛才的過程.

在哪些事件裡我們哪些事?

價值百萬美元的問題來了,在某個事件裡,我們該做什嗎?下面的表格列出了在什麼事件執行哪些邏輯處理的代碼。

Section

Event

Description

HttpModule

BeginRequest

This event signals a new request; it is guaranteed to be raised on each request.

HttpModule

AuthenticateRequest

This event signals that ASP.NET runtime is ready to authenticate the user. Any authentication code can be injected here.

HttpModule

AuthorizeRequest

This event signals that ASP.NET runtime is ready to authorize the user. Any authorization code can be injected here.

HttpModule

ResolveRequestCache

In ASP.NET, we normally use outputcache directive to do caching. In this event, ASP.NET runtime determines if the page can be served from the cache rather than loading the patch from scratch. Any caching specific activity can be injected here.

HttpModule

AcquireRequestState

This event signals that ASP.NET runtime is ready to acquire session variables. Any processing you would like to do on session variables.

HttpModule

PreRequestHandlerExecute

This event is raised just prior to handling control to the HttpHandler. Before you want the control to be handed over to the handler any pre-processing you would like to do.

HttpHandler

ProcessRequest

Httphandler logic is executed. In this section, we will write logic which needs to be executed as per page extensions.

Page

Init

This event happens in the ASP.NET page and can be used for:

· Creating controls dynamically, in case you have controls to be created on runtime.

· Any setting initialization.

· Master pages and the settings.

In this section, we do not have access to viewstate, postedvalues and neither the controls are initialized.

Page

Load

In this section, the ASP.NET controls are fully loaded and you write UI manipulation logic or any other logic over here.

Page

Validate

If you have valuators on your page, you would like to check the same here.

 

Render

It’s now time to send the output to the browser. If you would like to make some changes to the final HTML which is going out to the browser, you can enter your HTML logic here.

Page

Unload

Page object is unloaded from the memory.

HttpModule

PostRequestHandlerExecute

Any logic you would like to inject after the handlers are executed.

HttpModule

ReleaserequestState

If you would like to save update some state variables like session variables.

HttpModule

UpdateRequestCache

Before you end, if you want to update your cache.

HttpModule

EndRequest

This is the last stage before your output is sent to the client browser.

一個簡單的示範代碼

With this article, we have attached a sample code which shows how the events actually fire. In this code, we have created a ‘HttpModule’ and ‘Httphandler’ in this project and we have displayed a simple response write in all events, below is how the output looks like.
Below is the class for ‘HttpModule’ which tracks all events and adds it to a global collection.

public class clsHttpModule : IHttpModule

{

......

void OnUpdateRequestCache(object sender, EventArgs a)

{

objArrayList.Add("httpModule:OnUpdateRequestCache");

}

void OnReleaseRequestState(object sender, EventArgs a)

{

objArrayList.Add("httpModule:OnReleaseRequestState");

}

void OnPostRequestHandlerExecute(object sender, EventArgs a)

{

objArrayList.Add("httpModule:OnPostRequestHandlerExecute");

}

void OnPreRequestHandlerExecute(object sender, EventArgs a)

{

objArrayList.Add("httpModule:OnPreRequestHandlerExecute");

}

void OnAcquireRequestState(object sender, EventArgs a)

{

objArrayList.Add("httpModule:OnAcquireRequestState");

}

void OnResolveRequestCache(object sender, EventArgs a)

{

objArrayList.Add("httpModule:OnResolveRequestCache");

}

void OnAuthorization(object sender, EventArgs a)

{

objArrayList.Add("httpModule:OnAuthorization");

}

void OnAuthentication(object sender, EventArgs a)

{

objArrayList.Add("httpModule:AuthenticateRequest");

}

void OnBeginrequest(object sender, EventArgs a)

{

objArrayList.Add("httpModule:BeginRequest");

}

void OnEndRequest(object sender, EventArgs a)

{

objArrayList.Add("httpModule:EndRequest");

objArrayList.Add("<hr>");

foreach (string str in objArrayList)

{

httpApp.Context.Response.Write(str + "<br>") ;

}

}

}

Below is the code snippet for ‘HttpHandler’ which tracks ‘ProcessRequest’ event.

public class clsHttpHandler : IHttpHandler

{

public void ProcessRequest(HttpContext context)

{

clsHttpModule.objArrayList.Add("HttpHandler:ProcessRequest");

context.Response.Redirect("Default.aspx");

}

}

We are also tracking all the events from the ASP.NET page.

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

{

protected void Page_init(object sender, EventArgs e)

{

clsHttpModule.objArrayList.Add("Page:Init");

}

protected void Page_Load(object sender, EventArgs e)

{

clsHttpModule.objArrayList.Add("Page:Load");

}

public override void Validate()

{

clsHttpModule.objArrayList.Add("Page:Validate");

}

protected void Button1_Click(object sender, EventArgs e)

{

clsHttpModule.objArrayList.Add("Page:Event");

}

protected override void Render(HtmlTextWriter output)

{

clsHttpModule.objArrayList.Add("Page:Render");

base.Render(output);

}

protected void Page_Unload(object sender, EventArgs e)

{

clsHttpModule.objArrayList.Add("Page:UnLoad");

}}

Below is how the display looks like with all events as per the sequence discussed in the previous section.

放大ASP.NET頁面事件

在上面的章節,我們瀏覽了一個ASP.NET頁面請求的完整流程。其中最重要的是章節是ASP.NET頁面,我們還沒有討論它的細節,So,讓我們在這一章節花費一些精力來描述一下ASP.NET頁面事件的更多細節。

一些ASP.NET有2部分,一部分是在瀏覽器上展示的帶有HTML標籤的部分,另一個存放在HTML input元素上的表單的viewstate隱藏欄位。當頁面發布,在伺服器端,帶有viewstate和表單資料捆綁的ASP.NET控制項建立了html標籤, (原文:these HTML tags are created in to ASP.NET controls with viewstate and form data tied up together on the server,這句翻譯起來好彆扭,自己原文理解下吧),我們可以在後台代碼中擷取到所有的伺服器端控制項,可以執行和編寫自訂的邏輯然後把頁面渲染到瀏覽器

現在,對於這些作為ASP.NET控制項的可串連伺服器的HTML控制項,ASP.NET提供了大量的可供我們自訂邏輯的事件。我們只需要把我們所需要定義的任務或邏輯放在合適的事件裡面。(原文:Now between these HTML controls coming live on the server as ASP.NET controls, the ASP.NET page emits out lot of events which can be consumed to inject logic. Depending on what task / logic you want to perform, we need to put this logic appropriately in those events.這段翻譯有問題。)
Note: 大多數開發人員直接使用page_load處理所有的事情。這可不是一個好想法。So,它既要填充控制項,設定view state,設定主題等等,每一件事情發生在page load。So,如果我們能把自訂邏輯按照事件自然屬性的放入適當的事件中,那我們的代碼看起來會更清爽些。

Seq

Events

Controls Initialized

View state
Available

Form data
Available

What Logic can be written here?

1

Init

No

No

No

Note: You can access form data etc. by using ASP.NET request objects but not by Server controls.Creating controls dynamically, in case you have controls to be created on runtime. Any settinginitialization.Master pages and them settings. In this section, we do not have access to viewstate , posted values and neither the controls are initialized.

2

Load view state

Not guaranteed

Yes

Not guaranteed

You can access view state and any synch logic where you want viewstate to be pushed to behind code variables can be done here.

3

PostBackdata

Not guaranteed

Yes

Yes

You can access form data. Any logic where you want the form data to be pushed to behind code variables can be done here.

4

Load

Yes

Yes

Yes

This is the place where you will put any logic you want to operate on the controls. Like flourishing a combobox from the database, sorting data on a grid, etc. In this event, we get access to all controls, viewstate and their posted values.

5

Validate

Yes

Yes

Yes

If your page has validators or you want to execute validation for your page, this is the right place to the same.

6

Event

Yes

Yes

Yes

If this is a post back by a button click or a dropdown change, then the relative events will be fired. Any kind of logic which is related to that event can be executed here.

7

Pre-render

Yes

Yes

Yes

If you want to make final changes to the UI objects like changing tree structure or property values, before these controls are saved in to view state.

8

Save view state

Yes

Yes

Yes

Once all changes to server controls are done, this event can be an opportunity to save control data in to view state.

9

Render

Yes

Yes

Yes

If you want to add some custom HTML to the output this is the place you can.

10

Unload

Yes

Yes

Yes

Any kind of clean up you would like to do here.

關於源碼

This source code shows how the complete ASP.NET request cycle fires. You can download it from here.

References

I am not so smart to write this article by myself  , lot of things I have plugged from the below articles.

· Read more about IIS 7.0 life cycle http://msdn.microsoft.com/en-us/library/bb470252.aspx

· Intercepting filters http://msdn.microsoft.com/en-us/library/ms998536.aspx

· Explains how to implement Httphandlers and moduleshttp://msdn.microsoft.com/enus/library/system.web.httpapplication.aspx

· Httphandlers and Httpmodules :- http://www.15seconds.com/Issue/020417.htm

· Implementing security using modules and handlers http://joel.net/articles/asp.net2_security.aspx

· Difference between Httpapplication and global.asaxhttp://codebetter.com/blogs/karlseguin/archive/2006/06/12/146356.aspx

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

ASP.NET 生命週期(原文翻譯)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.