您的位置:首页 > 移动开发

通过Application统计网站访问人数和在线人数

2011-08-24 13:13 543 查看
这个需要在Global.asax文件里做文章,废话不多说,代码如下:
string path = "";
void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
int count=0;
if (!File.Exists(Server.MapPath("count.txt")))
{
File.Create(Server.MapPath("count.txt"));
StreamWriter sw = new StreamWriter(Server.MapPath("count.txt"));
//Write a line of text
sw.WriteLine("0");
}
else
{
StreamReader sr = new StreamReader(Server.MapPath("count.txt"));
count = Convert.ToInt32(sr.ReadLine());
}
path = Server.MapPath("count.txt");
Application["total"] = count;
Application["online"] = 0;
}
void Application_End(object sender, EventArgs e)
{
//  在应用程序关闭时运行的代码
using (StreamWriter sw = new StreamWriter(path))
{
//Write a line of text
sw.WriteLine(Application["total"].ToString());
}
}
void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码
Session.Timeout = 1;
Application.Lock();
Application["total"] = System.Convert.ToInt32(Application["total"]) + 1;
Application["online"] = System.Convert.ToInt32(Application["online"]) + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
// 或 SQLServer,则不会引发该事件。
Application.Lock();
Application["online"] = System.Convert.ToInt32(Application["online"]) - 1;
Application.UnLock();
}
在页面上随便拖个Lable,直接this.Label1.Text = Application["total"].ToString();这样就可以了

补充:这里是通过文件读写来实现的,当然,完全可以用XML或者数据库存储这些信息。如果想调试Application_End方法内的   内容,则运行网站之后,修改config然后保存即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: