C# – Where to implement Global.asax methods

asp.netcglobal-asaxvb.net

I am working on an ASP.Net application and currently the Global.asax contains the usual 5 methods:

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

However, I needed to implement the Application_AuthenticateRequest method as well, which is not a problem, I have just added it in Global.asax but in an another application I have seen this method being implemented elsewhere in another class which implements the IHttpModule interface.

How is this possible? The same app does not have the Application_AuthenticateRequest in Global.asax, their Global.asax looks like this:

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();
    }
}

What makes the Application_AuthenticateRequest method run?

Best Answer

I would first recommend you read about HTTP handlers and modules in ASP.NET. Then you will know that in an ASP.NET application you could have multiple modules registered which will run for every request and you have the possibility to subscribe to different events of the request lifecycle, the same way you could do it in Global.asax. The advantage of this approach is that you could put the modules into a reusable assembly that you use in multiple applications and which avoids you the need to repeat the same code over and over again.

Related Topic