6

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.

1
  • just noticed this was sort of a dupe. Not sure if there is new ground here to cover. Commented Jun 28, 2010 at 14:54

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.