【问题标题】:Where to implement Global.asax methods在哪里实现 Global.asax 方法
【发布时间】:2012-09-21 10:46:06
【问题描述】:

我正在开发一个 ASP.Net 应用程序,目前 Global.asax 包含常用的 5 种方法:

  1. Application_Start
  2. Application_End
  3. Session_Start
  4. Session_End
  5. Application_Error

但是,我还需要实现 Application_AuthenticateRequest 方法,这不是问题,我刚刚将它添加到 Global.asax 但在另一个应用程序中,我看到此方法在另一个实现的类的其他地方实现IHttpModule 接口。

这怎么可能?同一个应用在 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 方法运行?

【问题讨论】:

    标签: c# asp.net vb.net global-asax


    【解决方案1】:

    我首先建议您阅读HTTP handlers and modules in ASP.NET。然后您将知道在 ASP.NET 应用程序中您可以注册多个模块,这些模块将为每个请求运行,并且您可以订阅请求生命周期的不同事件,就像在 Global.asax 中一样。这种方法的优点是您可以将模块放入可在多个应用程序中使用的可重用程序集中,从而避免您一遍又一遍地重复相同的代码。

    【讨论】:

    • 谢谢,阅读有关 HTTP 模块的信息后,事情变得更加清晰了。
    【解决方案2】:

    基本上,我一直在查看的示例创建了自己的 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 的link 中所述:必须注册模块才能接收来自请求管道的通知。注册 HTTP 模块的最常用方法是在应用程序的 Web.config 文件中。在 IIS 7.0 中,统一请求管道还允许您通过其他方式注册模块,包括通过 IIS 管理器和通过 Appcmd.exe 命令行工具。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 2011-11-03
      • 2012-03-05
      • 2019-11-30
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多