在ASP.NET MVC中实现请求限制的最佳方法?

时间:2008-08-29 04:50:50

标签: asp.net-mvc throttling

我们正在尝试各种方法来限制给定时间段内的用户操作

  • 限制问题/答案帖子
  • 限制修改
  • 限制Feed检索

目前,我们正在使用缓存来简单地插入用户活动的记录 - 如果用户执行相同的活动时存在该记录,我们会限制。

使用缓存自动为我们提供过时的数据清理和用户滑动活动窗口,但它如何扩展可能是一个问题。

有哪些其他方法可以确保有效地限制请求/用户操作(强调稳定性)?

3 个答案:

答案 0 :(得分:231)

这是我们过去一年在Stack Overflow上使用的通用版本:

/// <summary>
/// Decorates any MVC route that needs to have client requests limited by time.
/// </summary>
/// <remarks>
/// Uses the current System.Web.Caching.Cache to store each client request to the decorated route.
/// </remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ThrottleAttribute : ActionFilterAttribute
{
    /// <summary>
    /// A unique name for this Throttle.
    /// </summary>
    /// <remarks>
    /// We'll be inserting a Cache record based on this name and client IP, e.g. "Name-192.168.0.1"
    /// </remarks>
    public string Name { get; set; }

    /// <summary>
    /// The number of seconds clients must wait before executing this decorated route again.
    /// </summary>
    public int Seconds { get; set; }

    /// <summary>
    /// A text message that will be sent to the client upon throttling.  You can include the token {n} to
    /// show this.Seconds in the message, e.g. "Wait {n} seconds before trying again".
    /// </summary>
    public string Message { get; set; }

    public override void OnActionExecuting(ActionExecutingContext c)
    {
        var key = string.Concat(Name, "-", c.HttpContext.Request.UserHostAddress);
        var allowExecute = false;

        if (HttpRuntime.Cache[key] == null)
        {
            HttpRuntime.Cache.Add(key,
                true, // is this the smallest data we can have?
                null, // no dependencies
                DateTime.Now.AddSeconds(Seconds), // absolute expiration
                Cache.NoSlidingExpiration,
                CacheItemPriority.Low,
                null); // no callback

            allowExecute = true;
        }

        if (!allowExecute)
        {
            if (String.IsNullOrEmpty(Message))
                Message = "You may only perform this action every {n} seconds.";

            c.Result = new ContentResult { Content = Message.Replace("{n}", Seconds.ToString()) };
            // see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
            c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
        }
    }
}

样本用法:

[Throttle(Name="TestThrottle", Message = "You must wait {n} seconds before accessing this url again.", Seconds = 5)]
public ActionResult TestThrottle()
{
    return Content("TestThrottle executed");
}

ASP.NET Cache就像一个冠军 - 通过使用它,您可以自动清理您的油门条目。随着我们不断增长的流量,我们没有看到这是服务器上的问题。

随意提供有关此方法的反馈;当我们使Stack Overflow更好时,你的Ewok fix会更快:)

答案 1 :(得分:67)

Microsoft为IIS 7提供了一个名为Dynamic IP Restrictions Extension for IIS 7.0-Beta的新扩展。

  

“IIS 7.0的动态IP限制是一个模块,可以防止对Web服务器和网站的拒绝服务和暴力攻击。这种保护是通过临时阻止HTTP客户端的IP地址来提供的,这些客户端的数量异常多并发请求或在很短的时间内发出大量请求。“   http://learn.iis.net/page.aspx/548/using-dynamic-ip-restrictions/

示例:

如果您在X requests in Y millisecondsX concurrent connections in Y milliseconds之后设置要阻止的条件,Y milliseconds将阻止IP地址,则会再次允许请求。

答案 2 :(得分:10)

我们使用从这个URL http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx借来的技术,不是用于限制,而是用于穷人的拒绝服务(D.O.S)。这也是基于缓存的,可能与您正在执行的操作类似。你是不是要限制D.O.S.攻击?路由器当然可以用来减少D.O.S;你认为路由器可以处理你需要的节流吗?