【问题标题】:How does Global.asax PostAuthenticateRequest event binding happen?Global.asax PostAuthenticateRequest 事件绑定是如何发生的?
【发布时间】:2011-01-13 07:51:01
【问题描述】:

如何使用 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 方法的?如何将方法更改为其他方法?

【问题讨论】:

    标签: asp.net .net events global-asax autoeventwireup


    【解决方案1】:

    Magic...,一种叫做Auto Event Wireup的机制,同理可以写

    Page_Load(object sender, EventArgs e) 
    { 
    } 
    

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

    MSDN description for System.Web.Configuration.PagesSection.AutoEventWireup property:

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

    AutoEventWireuptrue 时,处理程序会在运行时根据其名称和签名自动绑定到事件。对于每个事件,ASP.NET 搜索根据模式Page_eventname() 命名的方法,例如Page_Load()Page_Init()。 ASP.NET 首先查找具有典型事件处理程序签名的重载(即,它指定ObjectEventArgs 参数)。如果未找到具有此签名的事件处理程序,ASP.NET 将查找没有参数的重载。更多详情this answer

    如果您想明确地这样做,您可以编写以下代码

    public override void Init()
    {
        this.PostAuthenticateRequest +=
            new EventHandler(MyOnPostAuthenticateRequestHandler);
        base.Init();
    }
    
    private void MyOnPostAuthenticateRequestHandler(object sender, EventArgs e)
    {
    }
    

    【讨论】:

    • 我浪费了一个小时,因为它没有出现在 Intellisense 中,我想我可能不得不以某种方式订阅该事件。正要发帖询问如何实施该事件,但后来我想让我们试一试,看看我是否有任何错误,瞧!它工作:) 无论如何谢谢
    • 当心即。 Application_Start 或 Session_Start 只能通过 Auto Event Wireup 机制处理,您可以订阅的 HttpApplication 类上没有明确的事件。
    • 感谢您让我知道这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 2012-06-07
    相关资源
    最近更新 更多