Has something changed in data caching in ASP.NET-MVC3?

I need an application level cache in my MVC3 project.

I want to use something like this in the controller:

using System.Web.Caching; protected IMyStuff GetStuff(string stuffkey) { var ret = Cache[stuffkey]; if (ret == null) { ret = LoadStuffFromDB(stuffkey); Cache[stuffkey] = ret; } return (IMyStuff)ret; } 

This is not so because Cache ["foo"] does not compile as "System.Web.Caching.Cache - it is a" type ", but is used as a" variable ".

I see that Cache is a class, but there are many examples on the network when it is used as Session ["asdf"] in the controller, as if this property.

What am I doing wrong?

+4
source share
2 answers

The controller has a property called Session , but there is no property called Cache . You must use the static HttpRuntime.Cache property to get the Cache object. For instance:

 using System.Web.Caching; protected IMyStuff GetStuff(string stuffkey) { var ret = HttpRuntime.Cache[stuffkey]; if (ret == null) { ret = LoadStuffFromDB(stuffkey); HttpRuntime.Cache[stuffkey] = ret; } return (IMyStuff)ret; } 
+11
source

MVC uses newer methods for caching data like - [OutputCache (duration = 3)] You can also specify this in the web.config file as shown here: http://dotnetcodr.com/2013/02/07/caching-infrastructure -in-mvc4-with-c-caching-controller-actions / This is much more efficient and affordable if you work in MVC

  • however, if you want to use the previous caching method, you can consider System.Web.HttpContext.Current.Cache["variable"] = datasetresult or listObjectResult ie System.Web.HttpContext.Current.Cache ["POSSEData"] = MyDevObjBO.GetListOfObjects ();

then reassign as necessary: โ€‹โ€‹i.e. grdViewStuff.DataSource = (List) System.Web.HttpContext.Current.Cache ["POSSEData"];

0
source

All Articles