在web.config里面
<sessionState mode="InProc" cookieless="false" timeout="30" /> <!--三十分钟后,session失效-->
global.asax页面
<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Text" %>
<script runat="server">
protected void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
Application["onlinenum"] = 0; // 在线人数
}
protected void Application_End(object sender, EventArgs e)
{
// 在应用程序关闭时运行的代码
}
protected void Application_Error(object sender, EventArgs e)
{
// 在出现未处理的错误时运行的代码
}
protected void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码
Application.Lock();
Application["onlinenum"] = (int)Application["onlinenum"] + 1;
Application.UnLock();
//总人数访问统计
if (Session["total"] == null)
{
StreamReader objReader;
StreamWriter objWriter;
String sFile;
String sCount;
int iCount;
try
{
sFile = Server.MapPath("counter/counter.txt");
if (!File.Exists(sFile))
{
objWriter = File.CreateText(sFile);
objWriter.Write("0");
objWriter.Close();
}
objReader = File.OpenText(sFile);
sCount = objReader.ReadToEnd();
objReader.Close();
iCount = Int32.Parse(sCount);
iCount = iCount + 1;
sCount = iCount.ToString();
objWriter = File.CreateText(sFile);
objWriter.Write(sCount);
objWriter.Close();
Session["total"] = "set";
}
catch (Exception edd)
{
}
}
}
protected void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
// 或 SQLServer,则不会引发该事件。
Application.Lock();
Application["onlinenum"] = (int)Application["onlinenum"] - 1;
Application.UnLock();
}
</script>
前台调用代码:
using System;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
public partial class foot : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
lbl_onlineNum.Text = Application["onlinenum"].ToString();
StreamReader objReader;
string sFile;
string sCount= "";
int iCount;
try
{
sFile = Server.MapPath("counter/counter.txt");
objReader = File.OpenText(sFile);
sCount = objReader.ReadToEnd();
objReader.Close();
}
catch (Exception edd)
{
}
lbl_num.Text = sCount.ToString();
}
}
原帖地址:http://cfeng518.blog.163.com/blog/static/17467732200772311219489/