2012-07-09 147 views
3

我正在試驗緩存數據並保持失敗。正如你在下面的代碼中看到的那樣,我呼籲Web服務返回一個名爲「categories」的數組。這個電話很成功,我收到了信息。在用結果填充下拉列表之後,我使用Insert來存儲要緩存的信息。在頁面刷新(我想我應該說除回發之外的任何東西),我檢查緩存,看看信息是否存在。它從來沒有。抓我就這一個頭......Cache.Get always returns null

if (! IsPostBack) 
{ 
    //See if the results have been cached. With arrays and checking for null, you have to 
    //check the array itself before its elements can be checked. 
    string[] saveCatList = Cache.Get("Categories" + Session["sessionID"]) as string[]; 
    if (saveCatList == null || string.IsNullOrEmpty(saveCatList[0])) 
    { 
     WBDEMOReference.getcatlist_itemcategories[] categories; 
     strResult = callWebServ.getcatlist(Session["sessionID"].ToString(), 
        out strResultText, out dNumOfCat, out categories); 

     for (int i = 0; i < categories.Length; i++) 
     { 
      //ddCat is the ID number of the category drop down list 
      ddCat.Items.Add(new ListItem(categories[i].categorydesc.ToString(), 
             categories[i].categorynumber.ToString())); 
     } 

     //Store the array into cache. 'Cache.Remove' will remove the cache for that key 
     Cache.Insert("Categories" + Session["sessionID"], categories, null, 
      DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration); 
    } 
} 
+0

你調試了Session [「sessionID」]是什麼嗎?可能是它正在改變,並改變你正在查找緩存中的值的緩存鍵 – Dimitri 2012-07-09 18:47:11

+0

我做過,是的。 Session [「sessionID」]在Insert和Get time時相同。 – 2012-07-09 18:53:52

+2

是否有可能'categories'不是'string []'類型的?在這種情況下,'as'操作符會導致它變爲null – 2012-07-09 19:01:12

回答

2

我認爲sJhonny在評論中得到了它。您將categoriesWBDEMOReference.getcatlist_itemcategories的數組)放入緩存中,但在將其取出時請執行as string[]。類型與as關鍵字不匹配將導致null值。嘗試將as string[]更改爲as WBDEMOReference.getcatlist_itemcategories[]或者添加一個檢查,以查看它是否存在,而不使用as string[]強制轉換。

+0

這工作完美。我仍然在學習這個導入的服務引用是如何工作的 - 感謝清除它:) – 2012-07-09 20:40:31

1

看起來你正在使用的HttpContext緩存未在webcontext使用可以爲空,因此建議將緩存的httpRuntime。運行時緩存將始終在您的應用程序中可用於例如即使是在引擎蓋下,但在方案中使用控制檯應用程序

即使HttpContext的使用的httpRuntime緩存看起來運行緩存可能做的工作

我會很樂意刪除我的回答如果有人糾正我給出的提醒是錯誤的

+0

我嘗試使用'HttpRuntime.Cache.Get'和'HttpRuntime.Cache.Insert'修改代碼,但是我的結果是一樣的。 – 2012-07-09 20:08:23