Application-Level Code and global.asax
All
of the code shown so far has been written
at the page level, appearing either in an .aspx
file or in a code-behind file that implements a Page-derived class.
However, there needs to be a way to handle events and manipulate
properties at the application level as well, without regard to any
particular page. For this purpose there is the
global.asax
file.
global.asax
is a file that optionally can appear
in a web application’s root directory. If it is present, it can
contain code and settings that are automatically processed by the
ASP.NET framework at the appropriate times.
Session and Application Startup and Shutdown
Some applications may need to run
certain code whenever a new
session is started or is about to end, or
when the application as a whole is first started or is about to end.
This is done by placing code in the application’s
global.asax
file, as shown in Example 6-9.
Example 6-9. Responding to session and application start and end in a global.asax file
<script language="vb" runat="server"> Public Sub Session_OnStart( ) ' ... End Sub Public Sub Session_OnEnd( ) ' ... End Sub Public Sub Application_OnStart( ) ' ... End Sub Public Sub Application_OnEnd( ) ' ... End Sub </script>
Notice that code is placed in <script>
blocks.
The code in Example 6-9 defines four subroutines:
- Session_OnStart
Called by the ASP.NET framework when a session starts
- Session_OnEnd
Called by the ASP.NET framework when a session ends
- Application_OnStart
Called by ...
Get Programming Visual Basic .NET now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.