视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
ASP.net中网站访问量统计方法代码
2020-11-27 22:40:28 责编:小采
文档

一、建立一个数据表IPStat用于存放用户信息

我在IPStat表中存放的用户信息只包括登录用户的IP(IP_Address),IP来源(IP_Src)和登录时间(IP_DateTime),些表的信息本人只保存一天的信息,如果要统计每个月的信息则要保存一个月。因为我不太懂对数据日志的操作,所以创建此表,所以说我笨吧,哈哈。

二、在Global.asax中获取用户信息

在Global.asax的Session_Start即新会话启用时获取有关的信息,同时在这里实现在线人数、访问总人数的增量统计,代码如下:

代码如下:
void Session_Start(object sender, EventArgs e)
{
//获取访问者的IP
string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
//获取访问者的来源
string ipSrc;
//判断是否从搜索引擎导航过来的
if (Request.UrlReferrer == null)
{
ipSrc = "";
}
else
{
//获取来源地址
ipSrc = Request.UrlReferrer.ToString();
}
//获取访问时间
DateTime ipDatetime = DateTime.Now;
//保存IP信息到数据库中
IPControl cont = new IPControl();
cont.AddIP(ipAddress, ipSrc, ipDatetime);

//获取用户访问的页面
string pageurl = Request.Url.ToString();
//判断访问的是否是默认页
if (pageurl.EndsWith("IPStat.aspx"))
{
//锁定变量
Application.Lock();
//为页面访问量+1
Application["StatCount"] = int.Parse(Application["StatCount"].ToString()) + 1;
//解锁
Application.UnLock();
}

//锁定变量
Session.Timeout = 10; //设定超时为10分钟
Application.Lock();
Application["countSession"] = Convert.ToInt32(Application["countSession"]) + 1;  //访问总人数+1
Application["onlineWhx"] = (int)Application["onlineWhx"] + 1; //在线人数加+1
Session["login_name"] = null;
//解锁
Application.UnLock();
}

提醒一句,别忘了下面的代码,以实现在用户离线时,将在线人数减去1.

代码如下:
void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为 InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
// 或 SQLServer,则不会引发该事件。

//锁定变量
Application.Lock();
Application["onlineWhx"] = (int)Application["onlineWhx"] - 1; //在线人数减-1
Session["login_name"] = null;
//解锁
Application.UnLock();
}

三、将以上有关信息保存到数据库IPStat

创建了一个获取IP数据信息的类IPControl(),用来实现对数据库IPStat数据的操作,关于IPControl()类的内容,因为它是C#中对数据库的操作,以解Sql server 数据库,就能看懂它,这里就不作介绍了,请点击该链接查看。

为了实现将用户IP信息存入数据库,在上面代码中对IPControl()进行调用

代码如下:
//保存IP信息到数据库中
IPControl cont = new IPControl();
cont.AddIP(ipAddress, ipSrc, ipDatetime);

参数ipAddress为用户IP,ipSrc为用户来源, ipDatetime为用户进入时间。

四、创建定时器,定时操作有关数据

对以上IPSta数据库的数据,需要创建一个或者几个定时器,并在每天晚上24时前的10秒钟内统计一天的流量,然后将其删除,把统计结果保存到另一个数据表中,供页面显示昨日访问量是调用。定时器的创建和使用请点击创建一个或者几个定时器,供你参考。

以上不妥之处请批评指正。谢谢!

在ASP.net中网站访问量统计方法—获取IP数据信息的类

代码如下:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;

///
/// 获取IP数据信息的类
///
public class IPControl
{
//常量用来表示T-SQL语句中用到的变量名称
private const string PARM_IP_ADDRESS = "@IPAddress";
private const string PARM_IP_SRC = "@IPSrc";
private const string PARM_IP_DATETIME = "@IPDateTime";
//T-SQL语句
private const string SQL_INSERT_IPSTAT = "INSERT INTO IPStat VALUES(@IPAddress,@IPSrc,@IPDateTime)";
private const string SQL_DELETE_IPSTAT = "delete from IPStat WHERE DATEDIFF(d,ip_datetime,getdate())>30"; //只保留一个月的数据
private const string SQL_SELECT_TOTAL = "SELECT COUNT(*) FROM IPStat ";
private const string SQL_SELECT_TODAY = "SELECT COUNT(*) FROM IPStat WHERE DATEDIFF(d,ip_datetime,getdate())=0";
private const string SQL_SELECT_YESTERDAY = "SELECT COUNT(*) FROM IPStat WHERE DATEDIFF(d,ip_datetime,getdate())=1";
private const string SQL_SELECT_MONTH = "SELECT COUNT(*) FROM IPStat WHERE DATEDIFF(d,ip_datetime,getdate())<30 and DATEDIFF(mm,ip_datetime,getdate())=0";

public IPControl()
{
}
///
/// 保存IP数据信息到数据库
///
///
///
public void AddIP(string ipAddress,string ipSrc,DateTime ipDatetime)
{
//构建连接语句字符串
StringBuilder strSQL = new StringBuilder();
//创建表示QQ号的参数
SqlParameter[] parms = new SqlParameter[] { new SqlParameter(PARM_IP_ADDRESS, SqlDbType.NVarChar, 20),
new SqlParameter(PARM_IP_SRC, SqlDbType.NVarChar,80),
new SqlParameter(PARM_IP_DATETIME, SqlDbType.DateTime)};
SqlCommand cmd = new SqlCommand();

// 依次给参数赋值,并添加到执行语句中
parms[0].Value = ipAddress;
parms[1].Value = ipSrc;
parms[2].Value = ipDatetime;
foreach(SqlParameter parm in parms)
cmd.Parameters.Add(parm);

//定义对象资源保存的范围,一旦using范围结束,将释放对方所占的资源
using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionStringLocalTransaction))
{
//在执行字符串中加载插入语句
strSQL.Append(SQL_INSERT_IPSTAT);
conn.Open();

//设定SqlCommand的属性
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSQL.ToString();
//执行SqlCommand命令
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
//如果执行成功,返回true,否则false。
}
}
public string GetTotal()
{
//调用SqlHelper访问组件的方法返回第一行第一列的值
object count = SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_TOTAL, null);
//返回统计结果
return count.ToString();
}
public string GetToday()
{
//调用SqlHelper访问组件的方法返回第一行第一列的值
object count = SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_TODAY, null);
//返回统计结果
return count.ToString();
}
public string GetYesterday()
{
//调用SqlHelper访问组件的方法返回第一行第一列的值
object count = SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_YESTERDAY, null);
//返回统计结果
return count.ToString();
}
public string GetMonth()
{
//调用SqlHelper访问组件的方法返回第一行第一列的值
object count = SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_MONTH, null);
//返回统计结果
return count.ToString();
}
}

在Global.asax中使用定时器来统计在线人数和每天每月的访问量

一、在 Application_Start 中创建定时器

代码如下:
//以下为使用多个定时器System.Timers.Timer的处理方法
//用thread重新包一下,定义两个定时器
System.Threading.Thread myTimer_1 = new System.Threading.Thread(new System.Threading.ThreadStart(write_1));
myTimer_1.Start();
System.Threading.Thread myTimer_2 = new System.Threading.Thread(new System.Threading.ThreadStart(write_2));
myTimer_2.Start();

二、使用定时器每10分钟更新一次在线人数检查一次是否要存入一天流量的信息

代码如下:
//使用第一个定时器,每10分钟更新一次在线人数
private void write_1()
{
//以下使用System.Timers.Timer类 每间隔10分钟存一次数据
System.Timers.Timer myTimer1 = new System.Timers.Timer(600000); //实例化Timer类,设置间隔时间为600000毫秒(10分钟存一次总人数);
myTimer1.Enabled = true; //是否执行System.Timers.Timer.Elapsed事件;
myTimer1.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed); //到达时间的时候执行事件myTimer_Elapsed;
myTimer1.AutoReset = true; //设置是执行一次(false)还是一直执行(true);
}
//使用第二个定时器,
private void write_2()
{
//以下使用System.Timers.Timer类 每间隔10分钟检查一次是否要存入一天流量的信息
System.Timers.Timer myTimer2 = new System.Timers.Timer(600000); //实例化Timer类,设置间隔时间为600000毫秒(10分钟存一次总人数);
myTimer2.Enabled = true; //是否执行System.Timers.Timer.Elapsed事件;
myTimer2.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_peopleDay); //到达时间的时候执行事件myTimer_peopleDay;
myTimer2.AutoReset = true; //设置是执行一次(false)还是一直执行(true);
}

三、创建 myTimer过程来处理在线人数和统计每日、月、年的流量

代码如下:
//创建 myTimer_Elapsed 过程并定义第一个定时器事件,要用来处理在线人数的代码
private void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//如果现在的在现人数大于原有的在现人数,则替换数据表中的在现人数
int MaxOnline = Convert.ToInt32(Application["OnlineMax"]);
int MinOnline = Convert.ToInt32(Application["OnlineWhx"]);
if (MaxOnline < MinOnline)
{
SqlConnection con = Db.DB.createconnection();
con.Open();
SqlCommand cmd = new SqlCommand("update countpeople set totol='" + Application["countSession"].ToString() + "',OnLine=+'" + Application["onlineWhx"] + "',DataTimes='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'", con);
cmd.ExecuteNonQuery();
con.Close();
Application["OnlineMax"] = Application["OnlineWhx"]; //将现在线人数赋于OnlineMax
Application["dataTimes"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
else
{
//将总访问人数写入数据库
SqlConnection con = Db.DB.createconnection();
con.Open();
SqlCommand cmd = new SqlCommand("update countpeople set totol=" + Application["countSession"].ToString(), con);
cmd.ExecuteNonQuery();
con.Close();
}
}
//创建 myTimer_peopleDay 过程并定义第二个定时器事件,要用来统计每日、月、年的流量
private void myTimer_peopleDay(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
//当天晚上24时
if (DateTime.Now.Hour == 23)
{
if (DateTime.Now.Minute >= 50)
{
//当天晚上24时,写入一天的流量
//初始化一个iP数据访问对象
IPControl cont = new IPControl();
//获取今天访问量
Int32 countToday = Convert.ToInt32(cont.GetToday());
//获取本月访问量
Int32 countMonth = Convert.ToInt32(cont.GetMonth());

//存储过程名sp_InsertCountPeopleDay
SqlConnection con1 = Db.DB.createconnection();
con1.Open();
SqlCommand cmd1 = new SqlCommand("sp_InsertCountPeopleDay", con1);
cmd1.CommandType = CommandType.StoredProcedure; //存储过程名

//调用并设置存储过程参数
cmd1.Parameters.Add(new SqlParameter("@peopleDay", SqlDbType.Int));
cmd1.Parameters.Add(new SqlParameter("@dateTimes", SqlDbType.DateTime));

//给参数赋值
cmd1.Parameters["@peopleDay"].Value = countToday;
cmd1.Parameters["@dateTimes"].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

cmd1.ExecuteNonQuery();
con1.Close();

//在一个月的最后一天写入本月的访问量
//取本月最后一天(30或者31日)
DateTime lastDay = Convert.ToDateTime(DateTime.Now.AddMonths(1).ToString("yyyy-MM-01")).AddDays(-1);
int lastDay1 = DateTime.Now.Day; //取当前时间的日期
if (lastDay1.ToString() == lastDay.ToString()) //如果前日期等于本月最后一天的日期,则前本月的流量写入数据库
{
SqlConnection conM = Db.DB.createconnection();
conM.Open();
SqlCommand cmdM = new SqlCommand("sp_InsertCountPeopleMonth", conM);
cmdM.CommandType = CommandType.StoredProcedure; //存储过程名

//调用并设置存储过程参数
cmdM.Parameters.Add(new SqlParameter("@peopleMonth", SqlDbType.Int));
cmdM.Parameters.Add(new SqlParameter("@dateTimeMonth", SqlDbType.DateTime));

//给参数赋值
cmdM.Parameters["@peopleMonth"].Value = countMonth;
cmdM.Parameters["@dateTimeMonth"].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

cmdM.ExecuteNonQuery();
conM.Close();
}
}
}
}
catch
{

}
}

下载本文
显示全文
专题