【问题标题】:How in code to detect if session is enabled rather than just get an error如何在代码中检测是否启用了会话,而不仅仅是收到错误
【发布时间】:2018-11-08 09:01:12
【问题描述】:

如果我设置

@ENABLESESSIONSTATE = false

然后

session("foo") = "bar"

那么结果就是

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

这通常表明对程序流程的错误假设,我会跟踪并解决问题。

但是,在一组特定的情况下,我遇到了这样一种情况,即在每个页面请求上总是首先调用一段使用 session 的代码。它与性能监控有关。

此代码包含一个分叉 - 如果用户有会话,我们采用一种方式,否则我们采用另一种方式。

当然,如果因为我们引入了一些在禁用会话的情况下运行的代码而导致用户会话不存在,我们就会崩溃。

我可以解决它

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

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

【问题讨论】:

  • 您可以将逻辑包装在一个函数中以使其更易于使用,但至于使用 OERN 进行检查的方法,这将是我会做的。不过想知道,你能不能做一个IsObject(Session) 检查?
  • 没有考虑到 - 可能仍然会在未定义时抛出错误。我会尝试并回帖。
  • 兰基玛特是对的。做if isobject(session) then session("foo") = "bar" end if
  • 好的,不知道,谢谢。只是想在 2030 年 ASP 还没有死的时候为路过的人留下一个有用的足迹!

标签: session vbscript asp-classic session-variables


【解决方案1】:

为了让这个问题显示一个可接受的答案......

关于使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-19
    • 2018-02-19
    • 2015-06-13
    • 2021-09-11
    • 2017-05-24
    • 1970-01-01
    • 2023-03-12
    • 2013-02-06
    相关资源
    最近更新 更多