ASP.NET provides two events that help you manage user sessions: the Session_OnStart event, which is raised when a new session begins, and the Session_OnEnd event, which is raised when a session is abandoned or expires.
If the Global.asax file or Web.config file for an ASP.NET application is modified, the application will be restarted. If the current session-state mode is, any values stored in application state or session state will be lost. Be aware that some anti-virus software can update the last-modified date and time of the Global.asax or Web.config file for an application. For information on setting the session state mode, see .
The Session_OnStart Event
You can handle the Session_OnStart event by adding a subroutine named Session_OnStart to the Global.asax file. The Session_OnStart subroutine is run at the beginning of a request if the request begins a new session. A new session will be started if a request is made that does not contain avalue or if the SessionID property contained in the request references a session that has expired.
You can use the Session_OnStart event to initialize session variables as well as to track session-related information.
The Session_OnEnd Event
You can handle the Session_OnEnd event by adding a subroutine named Session_OnEnd to the Global.asax file. The Session_OnEnd subroutine is run when themethod has been called or when the session has expired. A session expires when the number of minutes specified by the property passes without a request being made for the session.
The Session_OnEnd event is supported only when the session stateproperty is set to InProc, which is the default. If the session state Mode is or , then the Session_OnEnd event in the Global.asax file is ignored. If the session state Mode is set to , then support for the Session_OnEnd event is determined by the custom session-state store provider.
You can use the Session_OnEnd event to clean up session-related information such as information for a user that is tracked in a data source by the SessionID value.
Session Events Example
The following code example shows a sample of the Session_OnStart and Session_OnEnd subroutines you can add to the Global.asax file. The subroutines defined in this example create a counter that keeps track of the number of application users actively using the application. Note that this example will function properly only when the session state Mode property is set to InProc, as the Session_OnEnd event is only supported for in-process session-state storage.
<script language="VB" runat="server"> Public Sub Application_OnStart() Application("UsersOnline") = 0 End Sub Public Sub Session_OnStart() Application.Lock() Application("UsersOnline") = CInt(Application("UsersOnline")) + 1 Application.UnLock() End Sub Public Sub Session_OnEnd() Application.Lock() Application("UsersOnline") = CInt(Application("UsersOnline")) - 1 Application.UnLock() End Sub </script>