2012-07-09 111 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