public override void OnActionExecuting(ActionExecutingContext filterContext) { var ckey = "APIRATE_" + AppUtils.GetClientIP(filterContext.HttpContext.Request); var counter = AppCaches.AppGet <RateCounter>(ckey); if (counter == null) { counter = new RateCounter(); AppCaches.AppSet(ckey, counter); } if (!counter.IsOverstepSeted) { this.Increase(counter); } if (counter.IsOverstepSeted) { if (AutoResult) { filterContext.Result = new ContentResult() { Content = "频率太快了,不要刷了" }; } else { filterContext.Controller.TempData["OUT_COUNT"] = "1"; } } }
/// <summary> /// 在当前频率计数域内为指定计数器递增。 /// </summary> /// <param name="counter">计数器对象</param> /// <returns>返回计数递增后,计数器是否超频。</returns> private bool Increase(RateCounter counter) { var result = counter.IsOverstepSeted; var now = DateTime.Now; var span = now - counter.TimePoint; if (span.TotalSeconds >= LimitDuration) { counter.Reset(now); counter.Count = 1; counter.Overstep = 0; counter.IsOverstepSeted = false; } else { ++counter.Count; if (!result && counter.Count > LimitCycleNumber) { ++counter.Overstep; counter.Reset(now); if (counter.Overstep >= LimitOverstep) { result = counter.IsOverstepSeted = true; } } } return(result); }