Website traffic statistics method code in ASP.net
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(); }
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(); }
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);
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(); } }
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();
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); }
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='" + 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 { } }
For more articles related to the website traffic statistics method code in ASP.net, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

In C language, the main difference between char and wchar_t is character encoding: char uses ASCII or extends ASCII, wchar_t uses Unicode; char takes up 1-2 bytes, wchar_t takes up 2-4 bytes; char is suitable for English text, wchar_t is suitable for multilingual text; char is widely supported, wchar_t depends on whether the compiler and operating system support Unicode; char is limited in character range, wchar_t has a larger character range, and special functions are used for arithmetic operations.

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

The char array stores character sequences in C language and is declared as char array_name[size]. The access element is passed through the subscript operator, and the element ends with the null terminator '\0', which represents the end point of the string. The C language provides a variety of string manipulation functions, such as strlen(), strcpy(), strcat() and strcmp().

char and unsigned char are two data types that store character data. The main difference is the way to deal with negative and positive numbers: value range: char signed (-128 to 127), and unsigned char unsigned (0 to 255). Negative number processing: char can store negative numbers, unsigned char cannot. Bit mode: char The highest bit represents the symbol, unsigned char Unsigned bit. Arithmetic operations: char and unsigned char are signed and unsigned types, and their arithmetic operations are different. Compatibility: char and unsigned char
