会话在超时asp.net上抛出错误

时间:2014-01-22 15:45:56

标签: asp.net session

如果错误存在,我在有效负载I测试中创建会话代码:

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

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

3 个答案:

答案 0 :(得分:0)

您无法在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);
}

答案 1 :(得分:0)

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

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

然后调用其ToString方法。您获得异常(NRE)的原因是因为密钥不会在会话中退出,而您尝试在其上调用ToString

答案 2 :(得分:0)

替换

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

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