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

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

I have some asp.net pages.

I'm just wondering why should I always check the Session object for null?

eg.

public static object GetSession(string key) { if (HttpContext.Current.Session != null) { return HttpContext.Current.Session[key]; } return null; } 
+6
source share
3 answers

Take a look at this page: What if the current ASP.NET session is null? . He got a pretty good explanation of the possibilities.

Edit

You would rarely find yourself in a situation where it is not known whether the session object is available and which you want to receive from it. In most cases, including those mentioned in other answers, HttpContext.Current.Session [key] will be null, but not HttpContext.Current.Session.

In most everyday scripts, the Session object will not be empty, and the code in your question will be redundant. Similarly, if you know that the Session object is null ahead of time, you should not even try to access it.

If your application accesses the Session object in an unusual scenario, when it may or may not be null, then your code will be a good way to process it, for example, described in the above question.

+4
source
  • If IIS reset your session will become null.
  • If the session times out, it will become zero.
  • There may be other reasons.

The checkpoint is to ensure that your page does not throw an ugly NullReferenceException if the session is null. This, if you check if it is null, you can refresh the page session or redirect to the login page, for example.

+2
source

If sessionState is disabled in the web.config file, it will probably be null

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

All Articles