当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.net中网站访问量统计方法代码

ASP.net中网站访问量统计方法代码

2017年12月12日  | 移动技术网IT编程  | 我要评论
一、建立一个数据表ipstat用于存放用户信息 我在ipstat表中存放的用户信息只包括登录用户的ip(ip_address),ip来源(ip_src)和登录时间(ip_

一、建立一个数据表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
{

}
}

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网