Global.asax magic functions Global.asax magic functions asp.net asp.net

Global.asax magic functions


It isn't really magical.. the ASP.NET Pipeline wires all of this up.

You can see the documentation regarding this here.

Specifically you will be interested in the parts below:

An HttpApplication object is assigned to the request.

Which consists of a list of events that are fired and in what order.

There are links all over that page (too many to contain here) that link off to various other pages with even more information.


ASP.NET automatically binds application events to handlers in the Global.asax file using the naming convention Application_event, such as Application_BeginRequest. This is similar to the way that ASP.NET page methods are automatically bound to events, such as the page's Page_Load event.

Source: http://msdn.microsoft.com/en-us/library/ms178473.aspx


To demystify the 'magic' of the accepted answer, the ASP.Net pipeline is automagically binding the HttpApplication events to the methods with the Application_EventName in the class. If (much like me) you would rather see the events explicitly bound to a handler these can be bound by overriding HttpApplication.Init() and Visual Studio will generate the handler method with the correct signature.

public override void Init(){  this.BeginRequest += MvcAppliction_BeginRequest;}private void MvcApplication_BeginRequest(object sender, EventArgs e){  ...}

There is an example of this method of binding events


ASP.Net itself creates it. Here is the flow as per MSDN -

  • User requests an application resource from the Web server.
  • ASP.NET receives the first request for the application.
  • ASP.NET core objects are created for each request.
  • An HttpApplication object is assigned to the request. In this step Global.asax will be processed and events will be associated automatically.
  • The request is processed by the HttpApplication pipeline. In this step the HttpApplication Global events are raised.

Here is the reference - ASP.Net Application Life Cycle.

From the reference - ASP.NET automatically binds application events to handlers in the Global.asax file using the naming convention Application_event, such as Application_BeginRequest.