Search code examples
c#asp.netpageviewsflooding

Earliest opportunity to catch a page view


I have a function I wish to be called on every page view, at the earliest possible opportunity. The code gets the users IP address, an increments a counter by 1 in a database.

This code is a basic flood limiter. If more than x requests are made in interval i then it temporarially bans that IP address. This is why the check needs to be as early as possible and on every page.

Calling in MasterPages Page_Init

This seems to work OK, however sometimes the counter increments by more than 1 (I assume if there's a URL re-write or redirect).

Calling in Global.asax on Session_Start

It seems to add ~30 to the counter on each page view.

What's the best way to catch a page view at the earliest possible opportunity, preferably without needing to change every single page on the site?


Solution

  • Inside Global.asax, you can hook to HttpApplication.BeginRequest, which is :

    the first event in the HTTP pipeline chain of execution when ASP.NET responds to a request

    This will fire for each request (for images, css, javascript, and so on). If you want to filter on pages only, you could write a HttpModule, that only increment your counter according to request extension.