Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rate Limiting with ASP.NET and the global.asax

What is a good simple way to only allow one request per IP per second using ASP.NET's global.asax file? Is there something else built-in to ASP.NET that I'm not thinking of?

If possible I'd like to only ignore requests that are multiple POSTs from jQuery's Ajax functions. I'm trying to fix a pervasive problem in an existing legacy app.

like image 595
BuddyJoe Avatar asked Jun 28 '10 14:06

BuddyJoe


1 Answers

This is a simple way to do it by using Application State since it applies to all users and sessions accessing your application.

In a new file called RequestManager.cs

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

Regards, Jonas Stensved

like image 116
Jonas Stensved Avatar answered Oct 06 '22 00:10

Jonas Stensved