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

23,273

Solution 1

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.

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

Share:
23,273
The Light
Author by

The Light

I love thinking and writing .NET applications and have over 13 years experience + MCPD, MCTS, MCAD, MCP.

Updated on May 23, 2020

Comments

  • The Light
    The Light almost 4 years

    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;
    
    }