1.介绍html
1)用MvcThrottle你能保护你的网站不受攻击、刷。git
2)你能够限制与设置多个不一样场景容许的IP,设置 每秒/分/天 容许访问IP。github
3)你能够定义限制,来处理全部请求。或者某个Controller、方法的范围。框架
2.使用ide
1)首先,请到github上下载框架,里面包括demo。可是demo写得我看不到,读者若是看得懂,建议不用阅读本文。网站
https://github.com/stefanprodan/MvcThrottlespa
2)引入MvcThrottle项目、包code
以下,咱们新建的一个MVC项目WebApplicationIPorm
3)在FilterConfig类中添加配置htm
1 public class FilterConfig 2 { 3 public static void RegisterGlobalFilters(GlobalFilterCollection filters) 4 { 5 const int secondCount = 5; 6 var throttleFilter = new ThrottlingFilter 7 { 8 //每秒钟最多请求secondCount次,每分钟最多请求secondCount*60次,依次类推 9 10 Policy = new ThrottlePolicy( 11 perSecond: secondCount, 12 perMinute: secondCount * 10, 13 perHour: secondCount * 10 * 5, 14 perDay: secondCount * 10 * 5 * 2) 15 { 16 IpThrottling = true 17 }, 18 Repository = new CacheRepository() 19 }; 20 filters.Add(throttleFilter); 21 22 filters.Add(new HandleErrorAttribute()); 23 } 24 }
4)在controller的方法设置访问限制
下面是表明用全局的IP访问限制:
[EnableThrottling]
下面是代码这个方法,每秒最多访问5次,每分钟10次:
[EnableThrottling(PerSecond = 5, PerMinute = 10)]
以上是FilterConfig的配置方法也是应用类库直接复制就行了
5)在Global中Application_Start方法中加入
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
6)若是须要修改请求返回参数或页面,找到MvcThrottle类库,打开ThrottlingFilter这个类,在该类的OnActionExecuting方法中修改以下:
1 if (rateLimit > 0 && throttleCounter.TotalRequests > rateLimit) 2 { 3 //log blocked request 4 if (Logger != null) Logger.Log(ComputeLogEntry(requestId, identity, throttleCounter, rateLimitPeriod.ToString(), rateLimit, filterContext.HttpContext.Request)); 5 6 //break execution and return 409 7 //var message = string.IsNullOrEmpty(QuotaExceededMessage) ? 8 // "HTTP request quota exceeded! maximum admitted {0} per {1}" : QuotaExceededMessage;//源代码 9 var message = string.IsNullOrEmpty(QuotaExceededMessage) ? 10 "您的操做太频繁,请稍后再试" : QuotaExceededMessage;//修改后 11 12 //add status code and retry after x seconds to response 13 filterContext.HttpContext.Response.StatusCode = (int)QuotaExceededResponseCode; 14 filterContext.HttpContext.Response.Headers.Set("Retry-After", RetryAfterFrom(throttleCounter.Timestamp, rateLimitPeriod)); 15 16 filterContext.Result = QuotaExceededResult( 17 filterContext.RequestContext, 18 string.Format(message, rateLimit, rateLimitPeriod), 19 QuotaExceededResponseCode, 20 requestId); 21 22 return; 23 }
把上面代码替换成
if (rateLimit > 0 && throttleCounter.TotalRequests > rateLimit) { filterContext.HttpContext.Response.Redirect("/Error.html"); //要跳转的页面 return; }
转载和参考https://www.cnblogs.com/alunchen/p/6203789.html