在ASP.NET中使用Global.asax檔案

來源:互聯網
上載者:User
    Global.asax 檔案,有時候叫做 ASP.NET 應用程式檔案,提供了一種在一個中心位置響應應用程式級或模組層級事件的方法。你可以使用這個檔案實現應用程式安全性以及其它一些任務。下面讓我們詳細看一下如何在應用程式開發工作中使用這個檔案。
  
    概述
  
     Global.asax 位於應用程式根目錄下。雖然 Visual Studio .NET 會自動插入這個檔案到所有的 ASP.NET 項目中,但是它實際上是一個可選檔案。刪除它不會出問題——當然是在你沒有使用它的情況下。.asax 副檔名指出它是一個應用程式檔案,而不是一個使用 aspx 的 ASP.NET 檔案。
  
    Global.asax 檔案被配置為任何(通過 URL 的)直接 HTTP 要求都被自動拒絕,所以使用者不能下載或查看其內容。ASP.NET 頁面架構能夠自動識別出對Global.asax 檔案所做的任何更改。在 Global.asax 被更改後ASP.NET 頁面架構會重新啟動應用程式,包括關閉所有的瀏覽器會話,去除所有狀態資訊,並重新啟動應用程式定義域。
  
    編程
  
    Global.asax 檔案繼承自HttpApplication 類,它維護一個HttpApplication 對象池,並在需要時將對象池中的對象分配給應用程式。Global.asax 檔案包含以下事件:
  
    ·Application_Init:在應用程式被執行個體化或第一次被調用時,該事件被觸發。對於所有的HttpApplication 對象執行個體,它都會被調用。
  
    ·Application_Disposed:在應用程式被銷毀之前觸發。這是清除以前所用資源的理想位置。
  
    ·Application_Error:當應用程式中遇到一個未處理的異常時,該事件被觸發。
  
    ·Application_Start:在HttpApplication 類的第一個執行個體被建立時,該事件被觸發。它允許你建立可以由所有HttpApplication 執行個體訪問的對象。
  
    ·Application_End:在HttpApplication 類的最後一個執行個體被銷毀時,該事件被觸發。在一個應用程式的生命週期內它只被觸發一次。
  
    ·Application_BeginRequest:在接收到一個應用程式請求時觸發。對於一個請求來說,它是第一個被觸發的事件,請求一般是使用者輸入的一個頁面請求(URL)。
  
    ·Application_EndRequest:針對應用程式請求的最後一個事件。
  
    ·Application_PreRequestHandlerExecute:在 ASP.NET 頁面架構開始執行諸如頁面或 Web 服務之類的事件處理常式之前,該事件被觸發。
  
    ·Application_PostRequestHandlerExecute:在 ASP.NET 頁面架構結束執行一個事件處理常式時,該事件被觸發。
  
    ·Applcation_PreSendRequestHeaders:在 ASP.NET 頁面架構發送 HTTP 頭給請求客戶(瀏覽器)時,該事件被觸發。
  
    ·Application_PreSendContent:在 ASP.NET 頁面架構發送內容給請求客戶(瀏覽器)時,該事件被觸發。
  
    ·Application_AcquireRequestState:在 ASP.NET 頁面架構得到與當前請求相關的目前狀態(Session 狀態)時,該事件被觸發。
  
    ·Application_ReleaseRequestState:在 ASP.NET 頁面架構執行完所有的事件處理常式時,該事件被觸發。這將導致所有的狀態模組儲存它們當前的狀態資料。
  
    ·Application_ResolveRequestCache:在 ASP.NET 頁面架構完成一個授權請求時,該事件被觸發。它允許緩衝模組從緩衝中為請求提供服務,從而繞過事件處理常式的執行。
  
    ·Application_UpdateRequestCache:在 ASP.NET 頁面架構完成事件處理常式的執行時,該事件被觸發,從而使緩衝模組儲存響應資料,以供響應後續的請求時使用。
  
    ·Application_AuthenticateRequest:在安全模組建立起目前使用者的有效身份時,該事件被觸發。在這個時候,使用者的憑據將會被驗證。
  
    ·Application_AuthorizeRequest:當安全模組確認一個使用者可以訪問資源之後,該事件被觸發。
  
    ·Session_Start:在一個新使用者訪問應用程式 Web 網站時,該事件被觸發。
  
    ·Session_End:在一個使用者的會話逾時、結束或他們離開應用程式 Web 網站時,該事件被觸發。
  
    這個事件列表看起來好像多得嚇人,但是在不同環境下這些事件可能會非常有用。
  
     使用這些事件的一個關鍵問題是知道它們被觸發的順序。Application_Init 和Application_Start 事件在應用程式第一次啟動時被觸發一次。相似地,Application_Disposed 和 Application_End 事件在應用程式終止時被觸發一次。此外,基於會話的事件(Session_Start 和 Session_End)只在使用者進入和離開網站時被使用。其餘的事件則處理應用程式請求,這些事件被觸發的順序是:
  
    ·Application_BeginRequest
  
    ·Application_AuthenticateRequest
  
    ·Application_AuthorizeRequest
  
    ·Application_ResolveRequestCache
  
    ·Application_AcquireRequestState
  
    ·Application_PreRequestHandlerExecute
  
    ·Application_PreSendRequestHeaders
  
    ·Application_PreSendRequestContent
  
    ·<<執行代碼>>
  
    ·Application_PostRequestHandlerExecute
  
    ·Application_ReleaseRequestState
  
    ·Application_UpdateRequestCache
  
    ·Application_EndRequest 
    這些事件常被用於安全性方面。下面這個 C# 的例子示範了不同的Global.asax 事件,該例使用Application_Authenticate 事件來完成通過 cookie 的基於表單(form)的身分識別驗證。此外,Application_Start 事件填充一個應用程式變數,而Session_Start 填充一個會話變數。Application_Error 事件顯示一個簡單的訊息用以說明發生的錯誤。 

    protected void Application_Start(Object sender, EventArgs e) {
   Application["Title"] = "Builder.com Sample";
  }
  protected void Session_Start(Object sender, EventArgs e) {
   Session["startValue"] = 0;
  }
  protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
   // Extract the forms authentication cookie
   string cookieName = FormsAuthentication.FormsCookieName;
   HttpCookie authCookie = Context.Request.Cookies[cookieName];
   if(null == authCookie) {
    // There is no authentication cookie.
    return;
   }
   FormsAuthenticationTicket authTicket = null;
   try {
    authTicket = FormsAuthentication.Decrypt(authCookie.Value);
   } catch(Exception ex) {
    // Log exception details (omitted for simplicity)
    return;
   }
   if (null == authTicket) {
    // Cookie failed to decrypt.
    return;
   }
   // When the ticket was created, the UserData property was assigned
   // a pipe delimited string of role names.
   string[2] roles
   roles[0] = "One"
   roles[1] = "Two"
   // Create an Identity object
   FormsIdentity id = new FormsIdentity( authTicket );
   // This principal will flow throughout the request.
   GenericPrincipal principal = new GenericPrincipal(id, roles);
   // Attach the new principal object to the current HttpContext object
   Context.User = principal;
  }
  protected void Application_Error(Object sender, EventArgs e) {
   Response.Write("Error encountered.");
  }
  
    這個例子只是很簡單地使用了一些Global.asax 檔案中的事件;重要的是要意識到這些事件是與整個應用程式相關的。這樣,所有放在其中的方法都會通過應用程式的代碼被提供,這就是它的名字為Global 的原因。
  
    這裡是前面的例子相應的 VB.NET 代碼:
  
  Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
   Application("Title") = "Builder.com Sample"
  End Sub
  Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
   Session("startValue") = 0
  End Sub
  Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As
  EventArgs)
   ’ Extract the forms authentication cookie
   Dim cookieName As String
   cookieName = FormsAuthentication.FormsCookieName
   Dim authCookie As HttpCookie
   authCookie = Context.Request.Cookies(cookieName)
   If (authCookie Is Nothing) Then
    ’ There is no authentication cookie.
    Return
   End If
   Dim authTicket As FormsAuthenticationTicket
   authTicket = Nothing
   Try
    authTicket = FormsAuthentication.Decrypt(authCookie.Value)
    Catch ex As Exception
    ’ Log exception details (omitted for simplicity)
    Return
   End Try
   Dim roles(2) As String
   roles(0) = "One"
   roles(1) = "Two"
   Dim id As FormsIdentity
   id = New FormsIdentity(authTicket)
   Dim principal As GenericPrincipal
   principal = New GenericPrincipal(id, roles)
   ’ Attach the new principal object to the current HttpContext object
   Context.User = principal
  End Sub
  
  Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
   Response.Write("Error encountered.")
  End Sub
  
    資源
  
    Global.asax 檔案是 ASP.NET 應用程式的中心點。它提供無數的事件來處理不同的應用程式級任務,比如使用者身分識別驗證、應用程式啟動以及處理使用者會話等。你應該熟悉這個可選檔案,這樣就可以構建出健壯的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.