2013-05-12 61 views
0

爲什麼我會在回發時收到Session [「Time」]變量的空引用異常,即使我已經在get請求中初始化了它。會話變量的空引用異常

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace WebApplication4 
{ 
    public partial class WebForm2 : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!IsPostBack) 
      { 
       Session["Time"] = DateTime.Now.ToString(); 
      } 
     } 
     protected void Button1_Click(object sender, EventArgs e) 
     { 
      Response.Write(Session["Time"].ToString()); 
     } 
    } 
} 

異常詳細信息:System.NullReferenceException:未將對象引用設置爲對象的實例。

+0

這裏沒有錯誤... – clamchoda 2013-05-12 03:57:25

+1

它是你的完整代碼嗎? – Arshad 2013-05-12 04:02:15

+0

檢查以下任一條件:http://support.microsoft.com/kb/306996 – 2013-05-12 04:02:15

回答

0

它不應該爲空,我只是測試你的代碼,它返回DateTime.Now.ToString()。

也許在你的global.asax或應用程序的某個地方清除或不存儲會話變量。

+0

在web.config文件下將SessionState模式設置爲InProc解決了問題。 – rtz87 2013-05-12 18:33:38

+0

好東西先生... – clamchoda 2013-05-12 19:08:04

-1

它很可能是空的,因爲您只在頁面加載時設置它,但由於任何原因在PostBack上設置,會話可以爲空。可以過期,或池回收和重置,等等。

頁面加載,從帖子後面可以有很長的時間距離。有人加載一個頁面,去喝咖啡,然後回來,然後按回車......會話在哪裏?

if (!IsPostBack) 
{ 
    Session["Time"] = DateTime.Now.ToString(); 
} 
// else If is PostBack the `Session["Time"]` can be null !!! 

也許你需要使用ViewState而不是會話

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      ViewState["Time"] = DateTime.Now.ToString(); 
     } 
    } 
    protected void Button1_Click(object sender, EventArgs e) 
    { 
     Response.Write(ViewState["Time"].ToString()); 
    } 

或檢查會話不爲空!