2014-01-22 17 views
0

我就与在我测试的有效载荷的会话的代码,如果错误存在:会抛出一个错误的超时asp.net

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" 
        /> 

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

回答

1

您应该检查会话密钥第一个像:

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

然后调用它的ToString方法。您得到例外(NRE)的原因是因为密钥不会在会话中退出,您正尝试对其调用ToString

+0

啊哈我得到了它......它的工作......但是这是我的第一个问题 第二是使会话永不过期? –

+0

@SamySammour,你不能这样做。您可以坚持使用Cookie或其他机制,但不能在会话中设置无限制的时间。这也不是一个好主意,因为会话是按用户维护的。 – Habib

+0

@SamySammour,你也可以看到这个http://stackoverflow.com/questions/1431733/keeping-asp-net-session-open-alive – Habib

1

不能在null执行ToString但正是这一点,你正在做的,如果会话值为null这里:

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

您需要单独检查null

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

更换

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

if (String.IsNullOrEmpty(Session["id"])) 
相关问题