示例#1
0
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            var key          = string.Concat(Name, "-", actionContext.HttpContext.Request.GetIp());
            var allowExecute = false;

            if (ContextBase.CacheRead(key) == null)
            {
                ContextBase.CacheInsertWithSeconds(key, true, Seconds);
                allowExecute = true;
            }

            if (allowExecute)
            {
                return;
            }

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

            actionContext.Result = new ContentResult {
                Content = Message.Replace("{n}", Seconds.ToString(CultureInfo.InvariantCulture))
            };
            // see 429 - Rate Limit Exceeded HTTP error
            actionContext.HttpContext.Response.StatusCode = 429;
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var seconds = Convert.ToInt32(TimeUnit);

            var key = string.Join(
                "-",
                seconds,
                filterContext.HttpContext.Request.HttpMethod,
                filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                filterContext.ActionDescriptor.ActionName,
                filterContext.HttpContext.Request.GetIp()
                );


            // increment the cache value
            var cnt         = 1;
            var cachedValue = ContextBase.CacheRead(key);

            if (cachedValue != null)
            {
                cnt = (int)cachedValue + 1;
            }

            ContextBase.CacheInsertWithSeconds(key, cnt, seconds);

            if (cnt <= Count)
            {
                return;
            }
            filterContext.Result = new ContentResult
            {
                Content = "You are allowed to make only " + Count + " requests per " + TimeUnit.ToString().ToLower()
            };
            // see 429 - Rate Limit Exceeded HTTP error
            filterContext.HttpContext.Response.StatusCode = 429;
        }