ASP .NET Check for Session

asp.netsessionsession-state

I'd like to check for the existence of the Session in a base page class before I use it, but I've found that if it does not exist, it'll throw an exception just by checking:

if (Session != null)
{
    Session.Remove("foo");
}

Will throw this exception:

Session state can only be used when enableSessionState is set to true, either in a
configuration file or in the Page directive. Please also make sure that
System.Web.SessionStateModule or a custom session state module is included in the
\\ section in the application configuration.

The check happens in the Load event of a base page class that all my aspx pages derive from. The app has the session enabled, and it has the module listed in the httpModules node. This is an app that uses session frequently, normally without a problem.

I get this error only on certain pages and most of the time it's not reliable. I know I should be doing something different to prevent the error, but I'm not sure what?

Am I calling the Session too early in the lifecycle maybe?
Am I not checking correctly for whether the session is available?

Best Answer

You can use a method like this to determine if the current request uses session:

    public static bool RequestHasSession
    {
        get
        {
            return (HttpContext.Current.Handler is IRequiresSessionState);
        }
    }

If you are not sure that you are even running in a web context you'd need to check that HttpContext.Current was not null beforehand.

Related Topic