6

In what situations the HttpContext.Current.Session can be null?

I'm having some asp.net pages.

I'm just wondering why I should be checking the Session object against null always?

e.g.

public static object GetSession(string key)
{

if (HttpContext.Current.Session != null)
{

return HttpContext.Current.Session[key];

}

return null;

}
Kiquenet
  • 14,494
  • 35
  • 148
  • 243
The Light
  • 26,341
  • 62
  • 176
  • 258

3 Answers3

4

Check out this page: What should I do if the current ASP.NET session is null?. It's got a pretty good explanation of the possibilities.

Edit

Rarely would you be a in a situation where it's unknown if the Session object is available and you want to access a value from it. In most instances, including those mentioned by other answers, HttpContext.Current.Session[key] will be null, but not HttpContext.Current.Session itself.

In most everyday coding scenarios the Session object will not be null, and the code in your question would be overkill. Likewise, if you know the Session object is null ahead of time, you should not even be attempting to access it.

If your application is accessing the Session object in the unusual scenario when it may or may not be null then your code would be a good way to handle it, such as those described in the above referenced question.

Community
  • 1
  • 1
Jake Braun
  • 1,172
  • 1
  • 13
  • 34
  • The question was why it can be null and whether we should be checking the Session object against null. – The Light Nov 05 '12 at 10:36
  • Edited my answer for you. The referenced question's accepted answer outlines the possibilities of why it could be null and I've added more information about whether you should be checking in the manner you've posted. – Jake Braun Nov 05 '12 at 15:14
2
  • If the IIS reset your Session will become null.
  • If the session timeout expires, it will become null.
  • There may be also other reasons.

The point of checking it is to prevent your page from throwing a ugly NullReferenceException in case the session is null. This, if you check if it is null, you can renew your page's session, or redirect to a login page, for example.

digaomatias
  • 1,164
  • 10
  • 21
0

If sessionState is turned off in the web.config it will probably be null

 <configuration>
  <system.web>
    <sessionState mode="Off" />
  </system.web>
</configuration>
Garvin
  • 477
  • 2
  • 10
  • 1
    this will cause the app to restart anyway. I don't see any valid reason to check Session object against null. – The Light Nov 05 '12 at 10:36