ASP.NET三种网站访问计数器[转]

本文介绍了三种实现网站访问量计数的方法:通过Cookies文件、Application内置对象及文本文件记录访问次数,确保即使在服务器异常情况下也能准确统计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<>、使用Cookies文件进行网站访问量计数

<%@Page Debug="True"%> ‘用于调试程序时,设置断点

<html>

<head><title>应用Cookies文件的访问计数器</title></head>

<body>

<h2 align="center"><b>使用Cookies文件进行网站访问量计数</b></h2>

<asp:label id="message" runat="server"/>

</body>

</html>

<script language="VB" runat="server">

sub Page_Load(sender 
as object,e as eventargs)

    dim vNumber 
as integer '定义一个保存访问次数的变量

       dim nickname 
as string

       nickname
="王庆坤"


       If Request.Cookies(
"vNumber") Is nothing then

           vNumber
=1 '如果第一次访问本站,访问次数为1

    
else

           vNumber
=Request.Cookies("vNumber").Value+1 '否则访问次数在原来的基础上加1

       end If

       Response.Cookies(
"vNumber").Value=vNumber '把访问次数写入Cookies文件

       Response.Cookies(
"vNumber").Expires=DateTime.Now.AddYears(1)

       message.Text
=nickname & ",您是第" & vNumber & "次访问本站,欢迎您!"

end sub

</script>

<>、使用Application内置对象进行网站访问量计数

说明:用于记录不同用户访问网站的次数

<html>

<head><title>使用Application对象对网站访问量进行计数</title></head>

<body>

<%

Application.Lock()

Application(
"UserCount")=Application("UserCount")+1

Application.UnLock()

Response.Write(Application(
"UserCount"))

%>

</body>

</html>

<>、使用文本文件保存网站访问量

说明:为避免服务器损坏或者突然停电等意外情况的发生,使用文件保存网站访问量

<html>

<head><title>使用StreamWriter和StreamReader对象进行网站计数</title></head>

<body>

<h2 align="center"><b>使用StreamWriter和StreamReader对象进行网站计数</b></h2>

<asp:label id="message" runat="server"/>

</body>

</html>

<%@Import Namespace="System.IO"%>

<script language="VB" runat="server">

sub Page_Load(sender 
as object,e as eventargs)

    dim VisiterCount 
as Long '定义计数器变量

       dim myFile 
as string     '定义文件路径变量

       myFile
=Server.MapPath("Count.txt")

       dim sw 
as StreamWriter

       dim sr 
as StreamReader

       
'如果该文件不存在建立文件,并写入1

       If File.Exists(myFile)
=false then

          sw
=new StreamWriter(myFile,false,Encoding.Default)

       sw.WriteLine(
"1")   '写入1

          sw.Close()

          message.Text
="您是第1位访客。" 

       
else

       
'读取文件

          sr
=new StreamReader(myFile,Encoding.Default)

          VisiterCount
=CLng(sr.ReadLine()) '读取一行,并转换成长整形

          sr.Close()

          
'写入文件

          sw
=new StreamWriter(myFile,false,Encoding.Default)

          VisiterCount
=VisiterCount+1   '将总数增加1

          sw.WriteLine(VisiterCount.ToString()) 
'写入一行,并覆盖原有数据

          sw.Close()

          message.Text
="您是第" & VisiterCount & "位访客。"

       end If

end sub

</script>
 

 

转载于:https://www.cnblogs.com/zhangsir/articles/1876526.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值