代码之家  ›  专栏  ›  技术社区  ›  Vanquished Wombat

如何在代码中检测会话是否已启用,而不仅仅是获取错误

  •  3
  • Vanquished Wombat  · 技术社区  · 7 年前

    如果我设置

    @ENABLESESSIONSTATE = false
    

    然后

    session("foo") = "bar"
    

    Microsoft VBScript运行时错误“800a0114”
    变量未定义“Session”
    ... 文件和行号

    它通常表示对程序流的错误假设,我将跟踪并修复该问题。

    然而,在一组特定的情况下,我遇到了这样一种情况:每次请求页面时,总是首先调用一段使用会话的代码。这与性能监控有关。

    但是当然,如果由于我们引入了一些在禁用会话的情况下运行的代码而缺少users会话,那么就会出现崩溃。

    我可以用

    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
    

    但我想知道是否有一种不那么老套的方法。

    1 回复  |  直到 7 年前
        1
  •  4
  •   Vanquished Wombat    7 年前

    关于使用isObject()方法的建议,结果并不好。以下asp。。。

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

    结果

    Microsoft VBScript运行时错误“800a01f4”

    /errortest.asp,第6行

    因此,会话对象似乎被标记为真正没有声明。

    我的结论是构造一个如下的函数。

    <%@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
    
    %>
    

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