Under ASP. net mvc, the number of requests per unit time of the same IP address is limited. asp. netmvc

Source: Internet
Author: User

Under ASP. net mvc, the number of requests per unit time of the same IP address is limited. asp. netmvc

Sometimes, when a user requests an Action under the Controller, we hope that within the unit interval, such as every second, every minute, every hour, every day, every week, limit the number of requests from the same IP address to an Action. What should we do?

 

The MvcThrottle of stefanprodan can solve this problem well, as well as other types of IP restrictions. Here: https://github.com/stefanprodan/MvcThrottle


Download the project from GitHub and open it locally.

 

Find the MvcThrottle class library, open the ThrottlingFilter class, and modify the OnActionExecuting method in the class as follows:

 

                        //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;
                        }

 

Replace the preceding

 

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

 

This allows you to upload the error.html file under the project root directory after several times.

 

Generate this class library. The class library MvcThrottle. dll is generated in the bin/Debug folder of the class library.

 

Create a project under ASP. net mvc 4.

 

Create a Library folder under the project root directory and copy the MvcThrottle. dll file.

 

REFERENCE The MvcThrottle. dll component in the Library folder.

 

In the App_Start folder, modify the FilterConfig class as follows:

 

    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);
        }
    }

 

Create HomeController and write it as follows:

 

    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});
        }
    }      

 

Generate a solution.

 

An error is reported! What Happened?

 

 

Originally, MvcThrottle was developed under ASP. net mvc 5.

 

There is a way. Re-open the MvcThrottle project class library, delete the original System. Web. Mvc from the reference, re-reference the local ASP. NET MVC4 version, and re-reference the local System. Web. Mvc.

 

Generate a new class Library, copy it to the Library folder, and generate a solution.

 

In the Home/Index. cshtml View:

 

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<Input type = "button" id = "btn" value = "request"/>
@section scripts
{
    <script type="text/javascript">
        $(function() {
            $('#btn').on("click", function() {
                $.post('@Url.Action("GetSth")',function(data) {
                    if (data.msg) {
Alert ("one request succeeded ");
                    } else {
Alert ("too many requests ");
                    }
                });
            });
        });
    </script>
}

 

When the number of requests exceeds the specified number of times per unit time interval, the "too many requests" prompt box is displayed.

 

In the Home/Other. cshtml View:

 

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

 

When the specified number of times exceeds the unit time interval, the preset error.html page is displayed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.