Global.asax PostAuthenticateRequest事件绑定是如何发生的?

Tux*_*Tux 8 .net asp.net events autoeventwireup global-asax

如何使用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)
        {    
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我打字的时候

protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
Run Code Online (Sandbox Code Playgroud)

它被成功调用.现在我想知道PostAuthenticateRequest是如何绑定到这个Application_OnPostAuthenticateRequest方法的?如何将方法更改为其他方法?

Pau*_*erø 15

Magic ...,一种叫做Auto Event Wireup的机制,与你可以编写的原因相同

Page_Load(object sender, EventArgs e) 
{ 
} 
Run Code Online (Sandbox Code Playgroud)

在您的代码隐藏中,该方法将在页面加载时自动调用.

MSDN对System.Web.Configuration.PagesSection.AutoEventWireup财产的描述:

获取或设置一个值,该值指示ASP.NET页面的事件是否自动连接到事件处理函数.

如果AutoEventWireuptrue,处理程序自动绑定到基于他们的名字和签名在运行时的事件.对于每个事件,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)
{
}
Run Code Online (Sandbox Code Playgroud)

  • 要小心,即.Application_Start或Session_Start只能通过Auto Event Wireup机制处理,在您可以订阅的HttpApplication类上没有明确的事件. (6认同)