华域联盟 .Net 在ASP.NET MVC下限制同一个IP地址单位时间间隔内的请求次数的解决方法

在ASP.NET MVC下限制同一个IP地址单位时间间隔内的请求次数的解决方法

在ASP.NET MVC下限制同一个IP地址单位时间间隔内的请求次数 

有时候,当用户请求一个Controller下的Action,我们希望,在单位时间间隔内,比如每秒,每分钟,每小时,每天,每星期,限制同一个IP地址对某个Action的请求次数。如何做呢?

stefanprodan的MvcThrottle能很好地解决这个问题,以及其它类型的IP限制问题。在这里:GitHub - stefanprodan/MvcThrottle: ASP.NET MVC Throttling filter
把项目从GitHub下载下来,在本地打开。

找到MvcThrottle类库,打开ThrottlingFilter这个类,在该类的OnActionExecuting方法中修改如下:

//check if limit is reached 
if (rateLimit > 0 && throttleCounter.TotalRequests > rateLimit)
{
  //log blocked request
  if (Logger != null) Logger.Log(ComputeLogEntry(requestId, identity, throttleCounter, rateLimitPeriod.ToString(), rateLimit, filterContext.HttpContext.Request));
  //break execution and return 409 
  var message = string.IsNullOrEmpty(QuotaExceededMessage) ?
  "HTTP request quota exceeded! maximum admitted {0} per {1}" : QuotaExceededMessage;
  //add status code and retry after x seconds to response
  filterContext.HttpContext.Response.StatusCode = (int)QuotaExceededResponseCode;
  filterContext.HttpContext.Response.Headers.Set("Retry-After", RetryAfterFrom(throttleCounter.Timestamp, rateLimitPeriod));
  filterContext.Result = QuotaExceededResult(
  filterContext.RequestContext,
  string.Format(message, rateLimit, rateLimitPeriod),
  QuotaExceededResponseCode,
  requestId);
  return;
}

把以上替换成

//check if limit is reached 
if (rateLimit > 0 && throttleCounter.TotalRequests > rateLimit)
{
filterContext.HttpContext.Response.Redirect("/Error.html");                               
return;
}  

让其在超过次数时,跳转到项目根目录下的Error.html文件。

生成该类库,类库MvcThrottle.dll生成在类库的bin/Debug文件夹下。

在ASP.NET MVC 4 下创建一个项目。

在项目根目录下创建一个Library文件夹,把刚才的MvcThrottle.dll拷贝其中。

引用Library文件夹下的MvcThrottle.dll组件。

在App_Start文件夹中,修改FilterConfig类如下:

public class FilterConfig 
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            var throttleFilter = new ThrottlingFilter
            {
                Policy = new ThrottlePolicy(perSecond: 1, perMinute: 10, perHour: 60 * 10, perDay: 600 * 10)
                {
                    IpThrottling = true
                },
                Repository = new CacheRepository()
            };
            filters.Add(throttleFilter);
        }
    }

创建HomeController,编写如下:

public class HomeController : Controller 
    {
        public ActionResult Index()
        {
            return View();
        }
        [EnableThrottling(PerSecond = 2, PerMinute = 5, PerHour = 30, PerDay = 300)]
        public ActionResult Other()
        {
            return View();
        }
        [HttpPost]
        [EnableThrottling(PerSecond = 2, PerMinute = 5, PerHour = 30, PerDay = 300)]
        public ActionResult GetSth()
        {
            return Json(new {msg=true});
        }
    }      

生成解决方案。

报错了!What Happened?

原来MvcThrottle是ASP.NET MVC 5下开发的。

有办法。重新打开MvcThrottle项目的类库,在引用中删除原来的System.Web.Mvc,重新引用本地ASP.NET MVC4版本,重新引用本地的System.Web.Mvc。

重新生成类库,重新拷贝到Library文件夹下,成功生成解决方案。

在Home/Index.cshtml视图中:

@{ 
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<input type="button" id="btn" value="请求"/>
@section scripts
{
    <script type="text/javascript">
        $(function() {
            $('#btn').on("click", function() {
                $.post('@Url.Action("GetSth")',function(data) {
                    if (data.msg) {
                        alert("请求成功一次");
                    } else {
                        alert("请求次数过多");
                    }
               });
           });
        });
    </script>
}

当在单位时间间隔内超过规定次数,就弹出"请求次数过多"提示框。

在Home/Other.cshtml视图中:

@{ 
    ViewBag.Title = "Other";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Other</h2>

当在单位时间间隔内超过规定次数,就跳转到预定的Error.html页了。

到此这篇关于在ASP.NET MVC下限制同一个IP地址单位时间间隔内的请求次数的解决方法的文章就介绍到这了,更多相关ASP.NET MVC请求次数限制内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

  • ASP.NET MVC限制同一个IP地址单位时间间隔内的请求次数
  • ASP.NET Core MVC控制器请求依赖注入
  • ASP.NET Core MVC解决控制器同名Action请求不明确的问题
  • ASP.NET Core MVC获取请求的参数方法示例
  • 浅谈ASP.NET MVC 防止跨站请求伪造(CSRF)攻击的实现方法
  • 请求如何进入ASP.NET MVC框架

本文由 华域联盟 原创撰写:华域联盟 » 在ASP.NET MVC下限制同一个IP地址单位时间间隔内的请求次数的解决方法

转载请保留出处和原文链接:https://www.cnhackhy.com/160032.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

下一篇

已经没有了

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部