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.
Note |
---|
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 |
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 a
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 the
The Session_OnEnd event is supported only when the session state
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.
Visual BasicВ | Copy Code |
---|---|
<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> |
C#В | Copy Code |
---|---|
<script language="C#" runat="server"> public void Application_OnStart() { Application["UsersOnline"] = 0; } public void Session_OnStart() { Application.Lock(); Application["UsersOnline"] = (int)Application["UsersOnline"] + 1; Application.UnLock(); } public void Session_OnEnd() { Application.Lock(); Application["UsersOnline"] = (int)Application["UsersOnline"] - 1; Application.UnLock(); } </script> |