2012-07-05 61 views
0

我有一種情況,我分配一些會話的價值。我有一種情況是代碼重複調用。此代碼有時會拋出對象null的錯誤。我沒有得到爲什麼發生這種情況,而我將值分配給it.My代碼如何解決對象空錯誤?

if (HttpContext.Current.Cache["Cache"] == null) 
      { 
       CreateChanhe(); 
       DataTable dtcache= HttpContext.Current.Cache["HNS Connection"] as DataTable; //CreateConnectString(CCMMUtility.Encryptdata(txtPin.Text)); 
       string sqlFilter = "Sp = '" + classses.DecryptString(HttpContext.Current.Request.Cookies["Cookies"].Values["sp"].ToString(), classses.SP) + "'"; 
       DataRow[] dr = dtcache.Select(sqlFilter); 
       if (dr.Length > 0) 
       { 
        String[] Con = new String[2]; 
        Con[0] = dr[0][0].ToString(); 
        Con[1] = dr[0][1].ToString(); 
        sp= Con[1]; 
        HttpContext.Current.Session["Name"] = dr[0][2].ToString(); 
       } 
      } 

當我嘗試做「添加監視」,而其調試說,「價值」有一定價值,但HttpContext.Current.Session [「Name」]爲空。有人可以讓我知道爲什麼會發生這種情況。

其實我正在創建一個緩存,然後從該緩存中填充會話。這是基於我的要求。

+1

此代碼行似乎對我來說,我想應該有一些其他代碼行導致此錯誤。你應該詳細說明。 – yogi

+0

嗨, 當您尚未分配任何會話變量值時,您可能正在檢查HttpContext.Current.Session [「Name」]值。 可能請發佈您的代碼,以便我可以分析更多。 –

+0

我已編輯了該代碼請審查。 – Visions

回答

0

我懷疑dr[0][2]爲空,所以當你打電話給.ToString()你會得到一個NRE。

+0

我已經檢查過它的值,它不爲空它有一定的價值。但是HttpContext.Current.Session [「Name」]爲空 – Visions

+0

@Visions與執行代碼的方法/功能相關。我猜!你的代碼在application_start或者沒有進行用戶請求的事件中執行。 – adatapost

+0

我認爲如果是這種情況(Application_Start),他會得到不同的異常。例如,如果您嘗試在集成管道模式下運行的IIS7 +下的Application_Start中嘗試使用HttpContext特定的東西,您將得到一個特定的異常,而不是NRE。對我來說,有兩種可能性:無論是我在答案中已經表達的那種,還是在後臺線程中運行此代碼,顯然他沒有訪問會話。 –

0

是否HttpContext.Current爲空?如果這樣包裝像這樣的空檢查:

if (HttpContext.Current != null) 
{ 
if (HttpContext.Current.Cache["Cache"] == null) 
      { 
       CreateChanhe(); 
       DataTable dtcache= HttpContext.Current.Cache["HNS Connection"] as      DataTable; //CreateConnectString(CCMMUtility.Encryptdata(txtPin.Text)); 
       string sqlFilter = "Sp = '" + classses.DecryptString(HttpContext.Current.Request.Cookies["Cookies"].Values["sp"].ToString(), classses.SP) + "'"; 
       DataRow[] dr = dtcache.Select(sqlFilter); 
       if (dr.Length > 0) 
       { 
        String[] Con = new String[2]; 
        Con[0] = dr[0][0].ToString(); 
        Con[1] = dr[0][1].ToString(); 
        sp= Con[1]; 
        HttpContext.Current.Session["Name"] = dr[0][2].ToString(); 
       } 
      } 
} 
+0

我試過這個,但又得到同樣的錯誤 – Visions

+0

你可以在HttpContext.Current.Session [「Name」]返回null的地方添加代碼嗎? –

+0

我在這裏爲會話分配了一些價值。 – Visions

相關問題