views:

92

answers:

3

On my login web page (i.e. the first page the user hits) I have code of this form:

public class MyPage : System.Web.UI.Page {
  private MyClass _obj = new MyClass();
  ...

MyClass has the constructor:

public MyClass() {
  var sess = HttpContext.Current.Session; // no problem here
  sess["MyValue"] = 123; // throws null ref exception coz sess is null
}

As I've commented, the call to sess["MyValue"] throws a null reference exception, because the HttpContext hasn't yet created the session object.

So when is it safe to start accessing the Session object? I don't want to give up on the inline declaration/initialization of _obj; that's very convenient for me! What alternatives do I have?

+10  A: 

You should be able to access the Session in or after the Page's OnInit event, or PreInit if you're that bothered. Before that, and you're dicing with death.

David Kemp
+1 for the info and the LOL :)
Shaul
A: 

You can look at the http pipeline. Rich Starhl has a nice article. . Your session objects are created/retrieved during aquireRequestState event. If you have HTTP Modules which intercept the request before this event, your session might not have been initialized

ram
+2  A: 

If the user is on the first page of the site, then the Session has no objects in it. You should definitely check the value before assigning to it.

if (Session["MyValue"] == null)
   Session.Add("MyValue", "");

Session["MyValue"] = "123";

You can also add the Global.asax file to the project. That is where you can handle the Session_Start event.

Eclipsed4utoo