我正在构建一个ASP.NET MVC站点,我想限制经过身份验证的用户使用该站点的某些功能的频率。
虽然我从根本上理解速率限制是如何工作的,但我无法想象如何以编程方式实现它而不会产生主要的代码气味。
你能否指出一个简单而强大的解决方案来解决这个问题,使用C#示例代码?
如果重要,所有这些功能目前都表示为仅接受HTTP POST
的操作。我最终可能还希望为HTTP GET
函数实现速率限制,所以我正在寻找一种适用于所有这些情况的解决方案。
答案 0 :(得分:18)
如果您使用的是IIS 7,则可以查看Dynamic IP Restrictions Extension。另一种可能性是将其实现为动作过滤器:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class RateLimitAttribute : ActionFilterAttribute
{
public int Seconds { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Using the IP Address here as part of the key but you could modify
// and use the username if you are going to limit only authenticated users
// filterContext.HttpContext.User.Identity.Name
var key = string.Format("{0}-{1}-{2}",
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
filterContext.ActionDescriptor.ActionName,
filterContext.HttpContext.Request.UserHostAddress
);
var allowExecute = false;
if (HttpRuntime.Cache[key] == null)
{
HttpRuntime.Cache.Add(key,
true,
null,
DateTime.Now.AddSeconds(Seconds),
Cache.NoSlidingExpiration,
CacheItemPriority.Low,
null);
allowExecute = true;
}
if (!allowExecute)
{
filterContext.Result = new ContentResult
{
Content = string.Format("You can call this every {0} seconds", Seconds)
};
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
}
}
}
然后装饰需要限制的动作:
[RateLimit(Seconds = 10)]
public ActionResult Index()
{
return View();
}
答案 1 :(得分:4)