Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache data on server in asp.net mvc 4?

Tags:

I am working on mvc4 web application. I want to cache some database queries results and views on server side. I used-

HttpRuntime.Cache.Insert() 

but it caches the data on client side. Please help.

like image 834
vivek Avatar asked Mar 19 '14 07:03

vivek


People also ask

How can store data in cache in ASP.NET MVC?

Store data into Cache in ASP.NET MVC in ASP.NET MVC Above action method first checks for the null value in HttpContext. Cache[“MyDate”] and it its null then saves current date in the Cache. Next line simply keep the data from the Cache into ViewBag.

How can use cache in ASP.NET MVC?

In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action. Output caching basically allows you to store the output of a particular controller in the memory.

What are the different caching techniques available in .NET MVC?

ASP.NET supports three types of caching: Page Output Caching [Output caching] Page Fragment Caching [Output caching] Data Caching.

How output cache works in MVC?

The output cache enables you to cache the content returned by a controller action. That way, the same content does not need to be generated each and every time the same controller action is invoked. Imagine, for example, that your ASP.NET MVC application displays a list of database records in a view named Index.


1 Answers

I'm using MemoryCache to store query results, and it's working fine so far.
Here are a few links that I've used to implement it.
- Using MemoryCache in .NET 4.0 (codeproject)
- Using MemoryCache in .NET 4.0 (blog entry)

As I read them now, I find them not that clear, so maybe there is a better link that I've lost somewhere.
Here is a sample of my code which I hope is clear enough so that you see how it works

public static class AgencyCacheManager {     private static MemoryCache _cache = MemoryCache.Default;      public static List<RefAgency> ListAgency     {         get         {             if (!_cache.Contains("ListAgency"))                 RefreshListAgency();             return _cache.Get("ListAgency") as List<Agency>;         }     }      public static void RefreshListAgency()     {         var listAgency = GetAllComplete();          CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();         cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddDays(1);          _cache.Add("ListAgency", listAgency, cacheItemPolicy);     } } 

And to retrieve the list from cache

public Agency FindBy(string agencyId) {     return AgencyCacheManager.ListAgency.SingleOrDefault(x => x.AgencyPartnerCode == agencyId); } 
like image 95
darkchico Avatar answered Oct 02 '22 23:10

darkchico