An ASP.NET application is made up of a collection of files including Web forms and assemblies that are stored in a virtual directory marked as an IIS application. When a resource in an ASP.NET application is requested , ASP.NET instantiates an HttpApplication object that then takes over the processing of the incoming request. The HttpApplication class defines the methods , properties, and events common to all application objects in an ASP.NET application. If you want to customize the behavior of an HttpApplication object, you can derive a class from the HttpApplication class and override the event handlers of the base class for various application-level events. An easy way to do this is by using the global.asax file. The global.asax FileThe global.asax file defines a class named Global that derives from the HttpApplication class. When ASP.NET notices that the global.asax file is present in the root directory of an application, rather than using the implicitly created HttpApplication object, ASP.NET creates instances of the class defined in the global.asax file to handle requests for an application.
Global Event HandlersThe global.asax file is an appropriate place to handle events that are not specific to a Web form, but rather apply to an application as a whole. I'll call these events global events and classify them in two categories application- and session-level events and per-request events . Application- and Session-level EventsApplication- and session-level events are fired to signal the start and end of the application or user session. These events can be handled using the predefined event handlers in the global.asax file shown in Table 4.8. Table 4.8. Application- and Session-level Event Handlers in the global.asax File
Per-request EventsThe event handlers shown in Table 4.9 are invoked for each individual page request processed by the HttpApplication object. Table 4.9. Per-request Event Handlers
As you can see from Table 4.9, you have complete control over how a request is processed. You can write code in any of these event handlers to modify the default behavior of ASP.NET. The following example uses the Application_BeginRequest() and Application_EndRequest() methods to determine the time it takes for each request to process and append this information with every response:
We used the Context object in the preceding program to store the begin time. The Context object provides access to all the information about the current HTTP request. It also exposes a key-value collection via the Items property in which you can add values that will be available for the life of the current request. |