asp.net中限制用户单位时间请求数

本文介绍了一个简单的请求计数器实现,用于限制用户在特定时间内的请求次数。通过使用C#和字典来跟踪每个用户的请求,当请求超过设定的最大值时,系统将阻止进一步的请求,直到重置时间到达。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1
{
    
public class RequestCounter
    {
        
private static Dictionary<string, RequestCounter> Counters = new Dictionary<string, RequestCounter>();
        
public const int MaxRequestCount = 3;
        
public const int ResetSeconds = 2;
        
public int CurrentCount { get;
            
private set; }
        
public string UserID { getset; }
        
private DateTime LastResetTime;
        
public bool AddCount()
        {
            DateTime now 
= DateTime.Now;
            
if ((now - LastResetTime).Seconds >= ResetSeconds)
            {
                
this.CurrentCount = 0;
                
this.LastResetTime = now;
            }
       this.CurrentCount++;
            if (this.CurrentCount <= MaxRequestCount)
                
return true;
            
else
                
return false;
        }
        
public static RequestCounter GetCounter(string userID)
        {
            
if (Counters.ContainsKey(userID))
                
return Counters[userID];
            
else
            {
                Counters[userID] 
= new RequestCounter();
                
return Counters[userID];
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    
public partial class _Default : System.Web.UI.Page
    {
        
protected void Page_Load(object sender, EventArgs e)
        {
            RequestCounter counter 
= RequestCounter.GetCounter("xhan");
            
bool canAccess = counter.AddCount();

            Response.Write(canAccess);
            Response.Write(counter.CurrentCount);

        }
    }
}


转载于:https://www.cnblogs.com/xhan/archive/2009/12/10/1621293.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值