Search code examples
sessionvbscriptasp-classicsession-variables

How in code to detect if session is enabled rather than just get an error


If I set

@ENABLESESSIONSTATE = false

then

session("foo") = "bar"

then the result is

Microsoft VBScript runtime error '800a0114'
Variable is undefined 'Session'
... file and line no

It would usually indicate a mistaken assumption regarding program flow and I would trace and fix the issue.

However, in a specific set of circumstances I have a case where a piece of code that uses session is always invoked first on every page request. It is to do with performance monitoring.

This code includes a fork - if the user has a session we go one way, if not we go another.

But of course where the users session is absent because we introduced some code that runs with session disabled, we get the crash.

I could solve it with

on error resume next 
session("foo") = "bar"
if err.number <> 0 then

   ' do the no-has-session fork

else

   ' do the has-session fork
end if
on error goto 0

But I wondered if there is a less hacky approach.


Solution

  • For the sake of having this question show an accepted answer....

    Regarding the suggestions for use of the isObject() approach, the results are not good. The following asp...

    <%@EnableSessionState=False%>
    <% option explicit
    
    response.write "session enabled=" &  IsObject(Session) 
    response.end
    
    %>
    

    results in

    Microsoft VBScript runtime error '800a01f4'

    Variable is undefined: 'Session'

    /errortest.asp, line 6

    Therefore it would appear that the session object is marked as truly not having been declared.

    My conslusion is to construct a function as below.

    <%@EnableSessionState=False%>
    <% option explicit
    
    response.write "session enabled=" &  isSessionEnabled()  ' <-- returns false 
    response.end
    
    function isSessionEnabled()
        dim s
    
        isSessionEnabled = true     ' Assume we will exit  as true - override in test 
        err.clear()                 ' Clear the err setting down
        on error resume next        ' Prepare to error
    
        s = session("foobar")       ' if session exists this will result as err.number = 0 
    
        if err.number <> 0 then 
            on error goto 0         ' reset the error object behaviour                  
           isSessionEnabled = false ' indicate fail - session does not exist.
           exit function            ' Leave now, our work is done
        end if
        on error goto 0             ' reset the error object behaviour
    end function                    ' Returns true if get to this point
    
    %>
    

    This is then used as

    If isSessionEnabled() then
        ' do something with session 
    else
        ' don't be messin with session.
    end if