Wednesday, June 27, 2007

Using the Global.asax File

Using the Global.asax File


The Global.asax File

In addition to writing UI code, developers can also add application level logic and event handling code into their Web applications. This code does not handle generating UI and is typically not invoked in response to individual page requests. Instead, it is responsible for handling higher-level application events such as Application_Start, Application_End, Session_Start, Session_End, and so on. Developers author this logic using a Global.asax file located at the root of a particular Web application's virtual directory tree. ASP.NET automatically parses and compiles this file into a dynamic .NET Framework class--which extends the HttpApplication base class--the first time any resource or URL within the application namespace is activated or requested.

The Global.asax file is parsed and dynamically compiled by ASP.NET into a .NET Framework class the first time any resource or URL within its application namespace is activated or requested. The Global.asax file is configured to automatically reject any direct URL request so that external users cannot download or view the code within.

Application or Session-Scoped Events

Developers can define handlers for events of the HttpApplication base class by authoring methods in the Global.asax file that conform to the naming pattern "Application_EventName(AppropriateEventArgumentSignature)". For example:



If the event handling code needs to import additional namespaces, the @ import directive can be used on an .aspx page, as follows:




The following sample illustrates the lifetime of Application, Session, and Request.








 




VB Application1.aspx

[Run Sample] | [View Source]
LateBreaking Samples:
  • J#

  • The first time the page is opened, the Start event is raised for the application and the session:





    The BeginRequest and EndRequest events are raised on each request. When the page is refreshed, only messages from BeginRequest, EndRequest, and the Page_Load method will appear. Note that by abandoning the current session (click the "End this session" button) a new session is created and the Session_Start event is raised again.


    Application or Session-Scoped Objects


    Static objects, .NET Framework classes, and COM components all can be defined in the Global.asax file using the object tag. The scope can be appinstance, session, or application. The appinstance scope denotes that the object is specific to one instance of HttpApplication and is not shared.




    Section Summary



    1. ASP.NET Framework applications can define event handlers with application-wide or session-wide scope in the Global.asax file.

    2. ASP.NET Framework applications can define objects with application-wide or session-wide scope in the Global.asax file.






    Copyright 2002 Microsoft Corporation. All rights reserved.

    0 Comments: