Home > Backend Development > C#.Net Tutorial > Website traffic statistics method code in ASP.net

Website traffic statistics method code in ASP.net

高洛峰
Release: 2017-01-23 17:27:26
Original
2586 people have browsed it

1. Create a data table IPStat to store user information

The user information I store in the IPStat table only includes the logged-in user’s IP (IP_Address), IP source (IP_Src) and login time (IP_DateTime ), I only save the information of these tables for one day. If I want to count the information for each month, I will save it for one month. I created this table because I don't know much about the operation of data logs, so call me stupid, haha.

2. Obtain user information in Global.asax

Obtain relevant information in Session_Start of Global.asax, that is, when a new session is enabled, and at the same time, increase the number of people online and the total number of visitors here. Volume statistics, the code is as follows:

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();
}
Copy after login

As a reminder, don’t forget the following code to reduce the number of people online by 1 when the user is offline.

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();
}
Copy after login

3. Subtract the above relevant information Save to database IPStat

Created a class IPControl() to obtain IP data information, which is used to operate the database IPStat data. Regarding the content of the IPControl() class, it is an operation of the database in C#. , you can understand it by understanding the Sql server database. I will not introduce it here. Please click on the link to view it.

In order to store the user IP information in the database, call IPControl() in the above code.

//保存IP信息到数据库中
IPControl cont = new IPControl();
cont.AddIP(ipAddress, ipSrc, ipDatetime);
Copy after login

The parameter ipAddress is the user IP, ipSrc is the user source, and ipDatetime is the user entry time.

4. Create a timer and regularly operate relevant data

For the above IPSta database data, you need to create one or several timers and set them within 10 seconds before 24:00 every night Count the traffic for one day, then delete it, and save the statistical results to another data table for the page to display the number of visits yesterday. To create and use timers, please click to create one or several timers for your reference.

Please criticize and correct any inaccuracies above. Thanks!

Website visit statistics method in ASP.net - class for obtaining IP data information

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();
}
}
Copy after login

Use timer in Global.asax to count the number of online people and daily and monthly visits

1. Create a timer in 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();
Copy after login

2. Use the timer to update the number of people online every 10 minutes and check whether you want to store the traffic information for one day

//使用第一个定时器,每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);
}
Copy after login

3. , Create the myTimer process to process the number of people online and count daily, monthly, and yearly traffic

//创建 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=&#39;" + Application["countSession"].ToString() + "&#39;,OnLine=+&#39;" + Application["onlineWhx"] + "&#39;,DataTimes=&#39;" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "&#39;", 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
{
}
}
Copy after login

For more articles related to the website traffic statistics method code in ASP.net, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template