Yesterday I had this problem where I needed to access the Session object from a webcontrol. I used HttpContext.Current.Session, after checking is HttpContext.Current was null. Then I've encountered a problem where HttpContext.Current was NOT null, neither were the Application, Response, Request and Server child objects, but Session was null.

After half an hour of searching on the web, I've decided to drill down on the problem and see what were the conditions under which it appeared. It seems someone had used the control in a UserControl that was loaded in the member declaration of the page. In other words, my WebControl was trying to access the Session object inside the constructor of a page. Apparently, the Session object is null in the constructor. Don't use private MyObject obj=new MyObject() anyway, since it breaks the separation of declaration and code, and don't try to access the Session object in the page Ctor.

My solution, after changing the offending piece of code, was to also change the WebControl to check if Session was null and if so, work without it. I also added a Debug.WriteLine('you are an idiot') message, for anyone encountering the same problem.



She is! As a matter of fact I know for sure she never instantiated a control in the member section of another control from then on ever again!


Post a comment