First of all, this is not a question about how to get the user’s IP address, as i know how to do that.
Basically, administrators of my website (ASP.NET MVC 3 Web Application) need the ability to block a certain IP address from submitting user content. So i’m storing the “IP Address” against user in our system. Cool.
My question is:
When (e.g at what times, page lifecycle events) should i be checked the user’s current IP address and saving to the database?
At the moment, i’m thinking of using session. That is, when i first create the session (e.g Session_OnStart()), grab the users IP address and stick it in the session. Then when the session ends (e.g Session_OnEnd()), i see if the IP address in session is different to that of the database. If it is, update the DB.
At the moment we’re using InProc, but there’s a good chance we’ll go to StateServer later on – and MSDN states Session_OnEnd is only available to InProc. So that might be a problem.
Any thoughts/alternatives to this approach?
EDIT
So i tried using Session_OnStart() to try and do the following thing:
If user is authenticated, get their IP address, get their last IP from the database, and if they different, update the database.
But the problem seems to be that Session_OnStart runs before Application_AuthenticateRequest – so it’s never passing the “is authenticated” check.
A good example is if a user logs into my website – using Forms Auth, which sets a cookie with an expiration date of a week (for example).
Then they come back a few days later – the Session_OnStart is fired – but they’re not authenticated yet. Even though the cookie is present – it hasn’t been processed into the http context yet.
So the Session_OnStart looks like a no go – any other ideas?
Since it’s asp.net MVC and you want it to run against all request, I’d consider looking at using a global action filter like the one described here http://weblogs.asp.net/gunnarpeipman/archive/2010/08/15/asp-net-mvc-3-global-action-filters.aspx