Speed โ€‹โ€‹Limit with ASP.NET and global.asax

What is a simple easy way to allow only one request per IP address using the global.asax ASP.NET file? Is there anything else built into ASP.NET that I don't think about?

If possible, I would just like to ignore requests that are multiple POST messages from jQuery Ajax functions. I am trying to fix a common problem in an existing legacy application.

+5
source share
1 answer

This is an easy way to do this using the state of the application, as it applies to all users and sessions accessing your application.

In the new RequestManager.cs file

 public static class RequestManager
{
    public static void Validate(HttpContext context)
    {


        if (context.Application["Blocklist"] == null)
            context.Application.Add("Blocklist", new Dictionary<string, DateTime>());

        Dictionary<string, DateTime> blocklist = context.Application["Blocklist"] as Dictionary<string, DateTime>;

        if (blocklist.ContainsKey(context.Request.UserHostAddress))
        {
            DateTime lastRequest = blocklist[context.Request.UserHostAddress];
            if (DateTime.Now.Subtract(lastRequest).TotalMilliseconds < 1000)
            {
                // End request
                context.Response.Write(string.Format("You'll have to wait for {0} milliseconds until next request", 1000 - DateTime.Now.Subtract(lastRequest).TotalMilliseconds));
                context.Response.End();
            }
            else
            {
                blocklist[context.Request.UserHostAddress] = DateTime.Now;
            }
        }
        else
        {
            blocklist.Add(context.Request.UserHostAddress, DateTime.Now);
        }

    }
}

In your Global.asax:

 protected void Application_BeginRequest(object sender, EventArgs e)
    {
        RequestManager.Validate(HttpContext.Current);
    }

,

+1

All Articles