ASP.NET在線人數和訪問人數總量統計
說明:限製在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();
}
}
原帖地址:https://cfeng518.blog.163.com/blog/static/17467732200772311219489/
最後更新:2017-04-02 22:16:12