The Light
The Light

Reputation: 27021

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

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;

}

Upvotes: 7

Views: 25813

Answers (3)

Jake Braun
Jake Braun

Reputation: 1382

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.

Upvotes: 4

digaomatias
digaomatias

Reputation: 1194

  • 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.

Upvotes: 2

Garvin
Garvin

Reputation: 487

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

 <configuration>
  <system.web>
    <sessionState mode="Off" />
  </system.web>
</configuration>

Upvotes: 0

Related Questions