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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With