Question

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?

Was it helpful?

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.

OTHER TIPS

Page_Init is the earliest event you can subscribe to in WebForms, so that is the way to go.

sometimes the counter increments by more than 1 (I assume if there's a URL re-write or redirect).

How is that a problem? A redirect is followed by another request, so it is another request. If you want to exclude those, you'll have to check in the latest event (Page_Unload in the case of WebForms) whether the response will perform a redirect and if so, subtract one from the counter, if that is the desired result.

Alternatively see Best way to implement request throttling in ASP.NET MVC? if you don't want to reinvent the wheel.

As per @mathieu's answer, you can swap Page_Init with HttpApplication.BeginRequest and Page_Unload with HttpApplication.EndRequest and perform the same logic, to make it independent of WebForms. You can hook up these events in Global.asax.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top