Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

}
like image 587
The Light Avatar asked Oct 31 '12 15:10

The Light


1 Answers

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.

like image 142
Jake Braun Avatar answered Sep 28 '22 02:09

Jake Braun