【问题标题】:session throw an error on timeout asp.net会话在超时 asp.net 上引发错误
【发布时间】:2014-01-22 23:48:51
【问题描述】:

如果错误存在,我会在我测试的有效负载中使用会话编写代码:

protected void Page_Load(object sender, EventArgs e)
     {
         if (String.IsNullOrEmpty(Session["id"].ToString())) QueryStringError.SessionNotFound(Response);
         else
        {

如果会话不存在,我会重定向到某个页面......但一段时间后我收到了这些错误:

Server Error in '/Redcrescent' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


    Line 11:     protected void Page_Load(object sender, EventArgs e)
    Line 12:     {
    Line 13:         if (String.IsNullOrEmpty(Session["id"].ToString())) QueryStringError.SessionNotFound(Response);
    Line 14:         else
    Line 15:         {

    Source File: c:\Users\Samy\Documents\Visual Studio 2010\WebSites\Redcrescent\User\UserPrivilegeManage.aspx.cs    Line: 13 

会话超时已完成,但为什么它给了我应该重定向的错误而不是抛出错误

在 web.config 文件中:

<sessionState cookieless="true"
      regenerateExpiredSessionId="true"
      timeout="525600" mode="InProc" stateNetworkTimeout="525600"
                  />

但仍然没有工作......有什么想法吗? 如何使会话永不过期?以及如何解决这些错误?

【问题讨论】:

    标签: asp.net session


    【解决方案1】:

    您应该首先检查会话密钥,例如:

    if(Session["id"]!= null)
    

    然后调用它的ToString 方法。您收到异常 (NRE) 的原因是密钥没有在会话中退出,并且您尝试在其上调用 ToString

    【讨论】:

    • 啊哈我明白了...它的工作...但这是我的第一个问题第二个是使会话永不过期?
    • @SamySammour,你真的不能那样做。您可以使用 cookie 或其他一些机制来持久化,但您不能在会话上设置无限超时。这也不是一个好主意,因为会话是按用户维护的。
    • @SamySammour,你也可以看到这个stackoverflow.com/questions/1431733/…
    • 它是一个 Web 应用程序,并且在选择要编辑和销毁之后的用户时激活会话......所以如果会话停留几天也不是问题......毕竟浏览器应该关闭,或者您应该选择另一个用户。但是这些会话的时间大约是 1 分钟,还不够,我该如何增加呢?
    【解决方案2】:

    您不能在null 上执行ToString,但如果会话值为空,您正在执行此操作:

    if (String.IsNullOrEmpty(Session["id"].ToString())) QueryStringError.SessionNotFound(Response);
    

    您需要单独检查null

    object id = Session["id"];
    if(id == null || String.IsNullOrEmpty(id.ToString())
    {
        QueryStringError.SessionNotFound(Response);
    }
    

    【讨论】:

      【解决方案3】:

      替换

      if (String.IsNullOrEmpty(Session["id"].ToString()))
      

      if (String.IsNullOrEmpty(Session["id"]))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-26
        • 2010-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多