Skip to main content
 首页 » 编程设计

c#之使用操作过滤器限制每个用户访问操作的次数

2024年02月23日14me-sa

假设我们有一个 Action ,我们想限制每个用户在一段时间内的访问次数,例如用户“A”在 5 分钟内不能访问示例 Action 超过 10 次,我很感兴趣在通过 Action 过滤器实现它时,有人知道吗?

请您参考如下方法:

您可以编写自定义授权过滤器,将每个用户对给定操作的调用次数存储在缓存中。通过配置缓存过期策略,该值将在时间过期后被自动驱逐。

public class AuthorizeWithThrottleAttribute : AuthorizeAttribute 
{ 
    private class Attempts 
    { 
        public int NumberOfAccess { get; set; } 
    } 
 
    public int Seconds { get; private set; } 
    public int Count { get; private set; } 
 
    public AuthorizeWithThrottleAttribute(int seconds, int count) 
    { 
        Seconds = seconds; 
        Count = count; 
    } 
 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
        var authorized = base.AuthorizeCore(httpContext); 
        if (!authorized) 
        { 
            return false; 
        } 
 
        var rd = httpContext.Request.RequestContext.RouteData; 
        var action = rd.GetRequiredString("action"); 
        var controller = rd.GetRequiredString("controller"); 
        // Remark: if you are using areas maybe you could also want 
        // to constrain the key per area 
 
        var key = string.Format("throttle-{0}-{1}-{2}", httpContext.User.Identity.Name, controller, action); 
        var policy = new CacheItemPolicy 
        { 
            AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(Seconds), 
        }; 
 
        // Here we are using the new caching API introduced in .NET 4.0: 
        // http://msdn.microsoft.com/en-us/library/system.runtime.caching.aspx 
        // If you are using an older version of the framework you could use 
        // the legacy HttpContext.Cache instead which offers the same expiration 
        // policy features as the new 
        var attempts = MemoryCache.Default.Get(key) as Attempts; 
        if (attempts == null) 
        { 
            attempts = new Attempts(); 
            MemoryCache.Default.Set(key, attempts, policy); 
        } 
 
        if (attempts.NumberOfAccess < Count) 
        { 
            attempts.NumberOfAccess++; 
            return true; 
        } 
        httpContext.Items["throttled"] = true; 
        return false; 
    } 
 
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    { 
        var throttled = filterContext.HttpContext.Items["throttled"]; 
        if (throttled != null && (bool)throttled) 
        { 
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict; 
            filterContext.Result = new ContentResult 
            { 
                Content = string.Format("You may only call this action {0} times every {1} seconds", Count, Seconds), 
                ContentType = "text/plain" 
            }; 
        } 
        else 
        { 
            base.HandleUnauthorizedRequest(filterContext); 
        } 
    } 
} 

然后装饰:

[AuthorizeWithThrottle(10, 5)] 
public ActionResult Foo() 
{ 
    return View(); 
}