簡體   English   中英

在哪里實現Global.asax方法

[英]Where to implement Global.asax methods

我正在使用ASP.Net應用程序,當前Global.asax包含通常的5種方法:

  1. Application_Start
  2. Application_End
  3. 會話開始
  4. 會話結束
  5. 應用程序錯誤

但是,我也需要實現Application_AuthenticateRequest方法,這不是問題,我剛剛將其添加到Global.asax中,但是在另一個應用程序中,我看到該方法在實現IHttpModule接口的另一個類的其他地方實現。

這怎么可能? 相同的應用Application_AuthenticateRequest在Global.asax中沒有Application_AuthenticateRequest ,它們的Global.asax如下所示:

void Application_BeginRequest(object sender, EventArgs e)
{
    myConfig.Init();
}

void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup
    myConfig.Init();
    if (InstallerHelper.ConnectionStringIsSet())
    {
        //initialize IoC
        IoC.InitializeWith(new DependencyResolverFactory());

        //initialize task manager
        TaskManager.Instance.Initialize(NopConfig.ScheduleTasks);
        TaskManager.Instance.Start();
    }
}

void Application_End(object sender, EventArgs e)
{
    //  Code that runs on application shutdown
    if (InstallerHelper.ConnectionStringIsSet())
    {
        TaskManager.Instance.Stop();
    }
}

是什么使Application_AuthenticateRequest方法運行?

我首先建議您閱讀ASP.NET中的HTTP處理程序和模塊 然后,您將知道在ASP.NET應用程序中可以注冊多個模塊,這些模塊將針對每個請求運行,並且可以訂閱請求生命周期的不同事件,就像在Global.asax中進行訂閱的方式一樣。 這種方法的優點是,您可以將模塊放入可重用的程序集中,以在多個應用程序中使用,並且避免了一次又一次地重復相同的代碼。

基本上,我一直在研究的示例創建了自己的HTTP模塊並將其注冊在web.config文件中:

他們創建了一個新的HTTP模塊,如下所示:

public class MembershipHttpModule : IHttpModule
{
    public void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        // Fires upon attempting to authenticate the user
        ...
    }

    public void Dispose()
    {
    }

    public void Init(HttpApplication application)
    {
        application.AuthenticateRequest += new EventHandler(this.Application_AuthenticateRequest);
    }
}

還將以下內容添加到web.config文件中:

<httpModules>
  <add name="MembershipHttpModule" type="MembershipHttpModule, App_Code"/>
</httpModules>   

如上面@Darin Dimitrov的鏈接所述:必須注冊模塊才能接收來自請求管道的通知。 注冊HTTP模塊的最常見方法是在應用程序的Web.config文件中。 在IIS 7.0中,統一請求管道還使您能夠以其他方式注冊模塊,包括通過IIS管理器和Appcmd.exe命令行工具。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM