ASP.Net Application - global.asax Files
(Page 6 of 8 )
global.asax performs a similar function in ASP.NET that global.asa performs in classic ASP. That is, it is an optional file that may contain code to respond to Application-or Session-level events. Like global.asa in classic ASP, there can be only one global.asax file per ASP.NET application. Unlike the global.asa file in classic ASP, which was parsed, the global.asax application file is compiled at runtime into a .NET managed assembly ultimately derived from the HttpApplication class. In addition to handling Application-and Session-level events, such as Session_OnStart, global.asax also allows you to handle events raised by HttpModules associated with your application (in fact, the Session state in ASP.NET is implemented as an HttpModule, so its events are already handled this way).
The global.asax file can be constructed one of two ways. The file can contain the event handlers and other code you want associated with your application directly, or it can reference a code-behind class file that contains the event handlers and code to associate with the application. Note that the code-behind used, if any, must inherit from the HttpApplication class in the System.Web namespace. The latter is the way that the global.asax files in ASP.NET applications created with Visual Studio .NET are constructed. Example 2-4 shows a typical global.asax file that uses code-behind, while Example 2-5 shows the code-behind file it uses.
Example 2-4 . global.asax using code-behind
<% -- Global.asax file-- %>
<%@ Application Codebehind="Global.asax.vb" Inherits=" <namespacename>. Global" %>
Example 2-5 . Code-behind file for global.asax in Example 2-4
'Global.asax.vb codebehind file
Imports System.Web
Imports System.Web.SessionState
Public Class Global
Inherits System.Web.HttpApplication
Sub Application_BeginRequest(ByVal sender As Object, _
ByVal e As EventArgs)
' Fires at the beginning of each request
End Sub
Sub Application_AuthenticateRequest(ByVal sender As
Object, _ ByVal e As EventArgs)
' Fires upon attempting to authenticate the user
End Sub
Sub Application_Error(ByVal sender As Object,
ByVal e As EventArgs)
' Fires when an error occurs
End Sub
End Class
We’ll discuss the uses of the global.asax file in more detail in Chapters 13 and 19.
This chapter is from ASP.NET in a Nutshell, by G. Andrew Duthie. (O'Reilly, 2003, ISBN: 0596005202). Check it out at your favorite bookstore today. Buy this book now.
|
Next: .aspx Files >>
More ASP.NET Articles
More By O'Reilly Media