- Why does Session_OnEnd() not fire?
There are two disparate scenarios here. One is when Session_OnEnd() doesn't get called, and the other is when the code within Session_OnEnd() fails. Don't get me wrong, when we get right down to it, Session_OnEnd() is unreliable. Do not create applications that rely on Session_OnEnd() to occur, because it doesn't always happen.
For some more information on this problem, see the following KB articles:
KB #247968 PRB: Connection to SQL Server from Session_OnEnd() Event May Fail
KB #277329 PRB: Cannot Access Network Resources in Application_OnEnd or Session_OnEnd Events
With that aside. A common cause of code in Session_OnEnd() failing is permissions. Note that under typical IIS configurations, the code being executed is running in the context of IWAM_<MACHINE_NAME>, not IUSR_<MACHINE_NAME>. So even though you may have fixed permissions for IUSR_<MACHINE_NAME>, you will need to follow the same process for IWAM_<MACHINE_NAME>. Though keep in mind that a resource that you are trying to access does not have to be on a remote machine for IUSR or IWAM to encounter permissions issues.
For some general help on using Session and Application objects, see the following article:
KB #300883 How To Use Session and Application Variables in an ASP Program
- Why can't I use Server.MapPath or Response.Redirect?
Session_OnEnd() does not support the Request, Response or Server objects. The only built-in objects you can use are session and application. So, for example, if you need to use a server.mapPath directive, store the fully qualified path in an application variable BEFORE the session ends. However, in limited testing, I was able to use these objects in files #included in global.asa (for the technique, see Article #2144).
Is there any way to get around this? Well, let's say you have a web app that stores session data in a database. When the session ends, you want to clean up that data, right? So you had a piece of code in Session_OnEnd() that deleted that data based on some unique identifier you stored in the session. If the user logs out properly, no problem. However, if they leave your site in any other way (e.g. closing their browser), the session data you stuffed in the database will be stored forever. See the SQL Server section of
Article #2491 for a way to schedule a regular cleanup of stale session data.