Asp.net

Global.asax PostAuthenticateRequest 事件綁定是如何發生的?

  • June 28, 2013

如何使用 Global.asax 的PostAuthenticateRequest事件?我正在關注本教程,它提到我必須使用PostAuthenticateRequest事件。當我添加 Global.asax 事件時,它創建了兩個文件,標記和程式碼隱藏文件。這是程式碼隱藏文件的內容

using System;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace authentication
{
   public class Global : System.Web.HttpApplication
   {    
       protected void Application_Start(object sender, EventArgs e)
       {    
       }

       protected void Session_Start(object sender, EventArgs e)
       {    
       }

       protected void Application_BeginRequest(object sender, EventArgs e)
       {
       }

       protected void Application_AuthenticateRequest(object sender, EventArgs e)
       {    
       }

       protected void Application_Error(object sender, EventArgs e)
       {    
       }

       protected void Session_End(object sender, EventArgs e)
       {    
       }

       protected void Application_End(object sender, EventArgs e)
       {    
       }
   }
}

現在當我輸入

protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e)

它被成功呼叫。現在我想知道PostAuthenticateRequest是如何綁定到這個Application_OnPostAuthenticateRequest方法的?如何將方法更改為其他方法?

魔術…,一種稱為Auto Event Wireup的機制,您可以編寫相同的原因

Page_Load(object sender, EventArgs e) 
{ 
} 

在您的程式碼隱藏中,該方法將在頁面載入時自動呼叫。

System.Web.Configuration.PagesSection.AutoEventWireup屬性的 MSDN 描述

獲取或設置一個值,該值指示 ASP.NET 頁面的事件是否自動連接到事件處理函式。

AutoEventWireupis時true,處理程序會在執行時根據它們的名稱和簽名自動綁定到事件。對於每個事件,ASP.NET 搜尋根據模式命名的方法Page_eventname(),例如Page_Load()Page_Init()。ASP.NET 首先查找具有典型事件處理程序簽名(即,它指定ObjectEventArgs參數)的重載。如果未找到具有此簽名的事件處理程序,ASP.NET 將查找沒有參數的重載。此答案中的更多詳細資訊。

如果您想明確地執行此操作,您將改為編寫以下內容

public override void Init()
{
   this.PostAuthenticateRequest +=
       new EventHandler(MyOnPostAuthenticateRequestHandler);
   base.Init();
}

private void MyOnPostAuthenticateRequestHandler(object sender, EventArgs e)
{
}

引用自:https://stackoverflow.com/questions/4677866