如何使用Global.asax的PostAuthenticateRequest事件?我正在关注
this tutorial,它提到我必须使用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方法的?如何将方法更改为其他方法?
解决方法
Magic …,一种叫做Auto Event Wireup的机制,与你可以编写的原因相同
Page_Load(object sender,EventArgs e) { }
MSDN description for System.Web.Configuration.PagesSection.AutoEventWireup
property:
Gets or sets a value indicating whether events for ASP.NET pages are automatically connected to event-handling functions.
当AutoEventWireup为true时,处理程序会根据其名称和签名在运行时自动绑定到事件.对于每个事件,ASP.NET都会搜索根据模式Page_eventname()命名的方法,例如Page_Load()或Page_Init(). ASP.NET首先查找具有典型事件处理程序签名的重载(即,它指定Object和EventArgs参数).如果找不到具有此签名的事件处理程序,ASP.NET将查找没有参数的重载.更多详情,请见this answer.
如果你想明确地这样做,你会写下面的内容
public override void Init() { this.PostAuthenticateRequest += new EventHandler(MyOnPostAuthenticateRequestHandler); base.Init(); } private void MyOnPostAuthenticateRequestHandler(object sender,EventArgs e) { }