统计网站在线人数

网站统计在线人数的功能已经很普遍,主要应用了全局变量application和session对象。描述说明就免了,大家都很熟悉简单贴一下代码,在Global.asax文件中写如下代码

 1  protected void Application_Start(object sender, EventArgs e)
 2         {
 3             HttpApplicationState applicationstate = GetApplicationstate();
 4             applicationstate["Count"] = 0;
 5         }
 6 
 7         private static HttpApplicationState GetApplicationstate()
 8         {
 9             //获取上下文对象
10             HttpContext context = HttpContext.Current;
11             //获得application对象
12             HttpApplicationState applicationstate = context.Application;
13             //在网站启动时默认当前在线人数为0
14             return applicationstate;
15         }
16 
17         protected void Session_Start(object sender, EventArgs e)
18         {
19 
20             HttpApplicationState applicationstate = GetApplicationstate();
21             //访问人数增加一个
22             applicationstate["Count"] = (int)applicationstate["Count"]+1;
23         }
24         protected void Session_End(object sender, EventArgs e)
25         {
26             HttpApplicationState applicationstate = GetApplicationstate();
27             //访问人数减少一个
28             applicationstate["Count"] = (int)applicationstate["Count"] - 1;
29         }

     然后在页面获取一下application["Count"]就可以了。在pageload事件中加上:this.lblCount.Text = this.Application["Count"].ToString();

在前台加一个label:

         当前在线人数:<asp:Label runat="server" ID="lblCount"></asp:Label>

统计在线人数就完成了。

你可能感兴趣的:(网站)