2012-10-27 67 views
3

我有一個c#.net Web應用程序。我創建會話變量,但是當我離開他們創建的頁面後,我嘗試閱讀它們時,我無法讀取它們。爲什麼我不能讀會話變量

創建網頁上的1

Session["UserName"] = "WhatEver"; 

然後我做

Response.Redirect("~/whatever.aspx"); 

,並嘗試讀取讀取會話變量在新的頁面

string userName = Session["UserName"].ToString(); 

我的Page_Load方法收到Object reference not set to an instance of an object.

爲什麼我收到此錯誤,我該如何解決該問題?

+0

請嘗試此Response.Redirect(「〜/ whatever.aspx」,false); – Karthik

+0

檢查您的global.asax或其他用戶控件附加在頁面2或母版頁你在哪裏使用「Session.Abandon」 –

+0

此鏈接解釋了爲什麼response.redirect會導致會話值丟失 - http://weblogs.asp.net/bleroy /archive/2004/08/03/Don_2700_t-redirect-after-setting-a-Session-variable-_2800_or-do-it-right_2900_.aspx – Krishna

回答

5

這可能會幫助:

Response.Redirect("~/whatever.aspx",false); 

this article

這不會中止該線程,從而節省了會話令牌。實際上,這個重載由RedirectFromLoginPage在內部使用。

+0

我試過這個,仍然得到了同樣的結果。 –

+0

@MartyGoetz是否能夠在重定向之前在同一頁上檢索會話值? – Karthik

0

可能sessionState在你config文件關閉

<sessionState mode="Off/> 

更改爲InProc [Depends中]

<sessionState mode="InProc" timeout ="60" /> 
+0

我檢查了web.config,我沒有設置「seesionState」。我也嘗試在web.config中添加。仍然沒有運氣。 –

0

我有完全相同的問題,我想辦法解決這個問題,但坦率地說,我不明白解決方案100%,無論如何,我所做的是從「添加新項目」菜單中爲我的項目創建一個「Global.asax」文件。只需將以下代碼複製粘貼到您的全局文件中即可。該文件中的代碼如下:

using System; 
using System.Collections.Generic; 
using System.Web; 
using System.Web.Security; 

using System.Text; 
using System.Data; 
using System.Data.SqlClient; 

namespace ENTER_YOUR_NAMESPACE 
{ 
    public class Global : System.Web.HttpApplication 
    { 
     void Application_Start(object sender, EventArgs e) 
     { 

     } 

     void Application_End(object sender, EventArgs e) 
     { 
      /* Code that runs on application shutdown */ 
      Session_End(sender, e); 
     } 

     void Application_Error(object sender, EventArgs e) 
     { 

     } 

     void Session_Start(object sender, EventArgs e) 
     { 

     }//end void Session_Start 

     void Session_End(object sender, EventArgs e) 
     { 

     }//end void Session_End 

    }//end class Global 
}//end namespace 
+0

請隨時對上面的代碼做任何調整,並且讓我知道如果你弄清楚它究竟發生了什麼,正如我以前說過的,我並不完全理解解決方案的邏輯! – M009

相關問題