search
HomeBackend DevelopmentC#.Net TutorialWebsite 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=&#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
{
}
}

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

Statement
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
.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment