views:

2190

answers:

3

In my web app, I do something like this to read the session variables:

if (HttpContext.Current.Session != null &&  HttpContext.Current.Session["MyVariable"] != null)
{
    string myVariable= (string)HttpContext.Current.Session["MyVariable"];  
}

I understand why it's important to check why HttpContext.Current.Session["MyVariable"] is null (the variable might not have been stored in the Session yet or the Session has been reset for various reasons) but why do I need to check if HttpContext.Current.Session is null?

My understanding is that the session is created automatically by asp.net therefore HttpContext.Current.Session should never be null. Is this assumption correct? If it can be null, does it mean I should also check it before storing something in it:

  if (HttpContext.Current.Session != null)
{
    HttpContext.Current.Session["MyVariable"]="Test";  
}
else
{
//what should be done in this case (if session is null)?
// is it possible to force the session to be created if it doesn't exist?
}
A: 

ASP.NET Technical Articles

SUMMARY: In ASP.NET, every Web page derives from the System.Web.UI.Page class. The Page class aggregates an instance of the HttpSession object for session data. The Page class exposes different events and methods for customization. In particular, the OnInit method is used to set the initialize state of the Page object. If the request does not have the Session cookie, a new Session cookie will be issued to the requester.

EDIT:

Session: A Concept for Beginners

SUMMARY: Session is created when user sends a first request to the server for any page in the web application, the application creates the Session and sends the Session ID back to the user with the response and is stored in the client machine as a small cookie. So ideally the "machine that has disabled the cookies, session information will not be stored".

adatapost
+9  A: 

Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:

If you only have code in pages, you won't run into this. Most of my ASP .NET code uses Session without checking for null repeatedly. It is, however, something to think about if you are developing an IHttpModule or otherwise is down in the grittier details of ASP .NET.

Edit

In answer to the comment: Whether or not session state is available depends on whether the AcquireRequestState event has run for the request. This is where the session state module does it's work by reading the session cookie and finding the appropiate set of session variables for you.

AcquireRequestState runs before control is handed to your Page. So if you are calling other functionality, including static classes, from your page, you should be fine.

If you have some classes doing initialization logic during startup, for example on the Application_Start event or by using a static constructor, Session state might not be available. It all boils down to whether there is a current request and AcquireRequestState has been run.

Also, should the client have disabled cookies, the Session object will still be available - but on the next request, the user will return with a new empty Session. This is because the client is given a Session statebag if he does not have one already. If the client does not transport the session cookie, we have no way of identifying the client as the same, so he will be handed a new session again and again.

driis
What if you read your session variables in a static class called from a page for example? Will the session alway exist?
Anthony
Anthony, I updated the answer.
driis
Thanks Driis. Very clear answer.
Anthony
A: 

One way of using session variables is to add properies to a Page class that is inherited by all your pages. In this case you can wrap each session variable and do the required null checks. We use this pattern which works well:

public string MyVariable
        {
            get
            {
                if (Session["MyVariable"] == null || Session["MyVariable"].ToString().Trim() == String.Empty)
                {
                    Session["MyVariable"] = String.Empty;
                }

                return Session["MyVariable"].ToString().Trim();
            }
            set
            {
                Session["MyVariable"] = value;
            }
        }
Mark Redman
Assuming you're reading and writing the session variables on a Page, MasterPage or User Control, you dont need to worry about the state of the session beforehand.
Mark Redman
What if you put the above code in a static class called from a page for example? Will the session alway exist?
Anthony