Use the Application object in ASP. NET to implement the simple online count statistics function
This article describes how to use the Application object in ASP. NET to implement the simple online count statistics function. This article provides implementation steps and corresponding code examples. For more information, see
Note: I am reviewing ASP. NET recently. I will make some demo programs to help you better understand the situation and share them with you.
1. Create an ASP. NET Website and edit the Global. asax file. The modified file content is as follows.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<% @ Application Language = "C #" %> <Script runat = "server"> Void Application_Start (object sender, EventArgs e) { // Code that runs when the application starts Application ["CurrentUserCount"] = 0; } Void Application_End (object sender, EventArgs e) { // Code that runs when the application is closed } Void Application_Error (object sender, EventArgs e) { // Code that runs when an unhandled error occurs } Void Session_Start (object sender, EventArgs e) { // The code that runs when the new session starts Application. Lock (); Application ["CurrentUserCount"] = (int) Application ["CurrentUserCount"] + 1; Application. UnLock (); } Void Session_End (object sender, EventArgs e) { // The code that runs when the session ends. // Note: The Session_End event is triggered only when the sessionstate mode in the Web. config file is set to InProc. // If the session mode is set to StateServer // Or SQLServer, the event is not triggered. Application. Lock (); Application ["CurrentUserCount"] = (int) Application ["CurrentUserCount"]-1; Application. UnLock (); } </Script> |
2. Modify the Web. config file, add the following configuration nodes, and add new configuration nodes. Node.
The Code is as follows:
3. Add a label to the Default. aspx file to display the current number of online users.
The Code is as follows:
Protected void Page_Load (object sender, EventArgs e)
{
This. Label1.Text = Application ["CurrentUserCount"]. ToString ();
}
4. Use IE and Chrome to access the application. The result is displayed.