In my ASP.NET application, i have a procedure that log all exceptions to a file (using Application_Error() and global.asax). Inside that procedure, I log several things like current datetime, user name and such.
It works well, however, if someone (that is already logged) try to access a page that doesn’t exists (eg : http://www.mywebsite.com/foo.aspx) current user name information cannot be accessed from procedure, because System.Web.HttpContext.Current.Session is null. At first, i was thinking that session has been lost. it is not true, because if i press back i can still use the website (links still works without being redirected to login page).
What is the reason of session being null if a ressource is not found ? is it because session object is only initialized by asp after he know which page to deliver ? or maybe something is not configurated correctly on my website ?
Take a look at the ASP.NET event lifecycle:
http://msdn.microsoft.com/en-us/library/bb470252.aspx
In particular, how
HttpApplicationprocesses your request. Note, that beforeBeginRequest(no.3) andAcquireRequestState(no.12) there are at least few important events.Now then, your session is available only after
AcquireRequestState. If you have any error in one of prior events, you’ll get the null reference onSession.“Resource not found” is just one example but in general you have to be prepared that
Sessionis just not available in early events of the processing pipeline.