Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP .NET Check for Session

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?

like image 804
Pete Michaud Avatar asked Jul 14 '09 13:07

Pete Michaud


2 Answers

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.

like image 108
Rob Kent Avatar answered Oct 10 '22 21:10

Rob Kent


You can make your check safer - Page.Session wraps a null check around the Context.Session property. So you should be able to retrieve Context.Session and check if it's null. If it is then session state is not available.

But it should be available in Page_Load(), so that points to problems elsewhere :)

like image 45
blowdart Avatar answered Oct 10 '22 21:10

blowdart