In this blog, we will see how to implement caching in MVC?
Before writing MVC code for caching, you should be very much clear about “What is Caching?”
What is Caching?
Cache means to store it in a temp memory for future use. Caching is often used to store information that’s frequently served to users in a faster manner. The purpose of caching is to enhance the performance of a web page. You may read this blog – Caching in ASP.Net
How to implement Caching in MVC?
You may apply caching either via web.config file or via adding an attribute to an action method in a controller class.
Let’s see how to apply caching for an Action method.
Output Cache With Duration
Caching can be implemented by adding OutputCache attribute
[OutputCache(Duration=120)] public ActionResult Index() { ViewBag.CurrTime = DateTime.Now.ToString(); return View(); } |
Output Cache with CacheProfile
We can also apply caching to Action method by using Cache Profile.
Add below snippet in web.config file within <system.web> … </system.web>
<caching> <outputCacheSettings> <outputCacheProfiles> <addname=“CacheProfile1“duration=“120“varyByParam=“none“/> <addname=“CacheProfile2“duration=“10“varyByParam=“none“/> </outputCacheProfiles> </outputCacheSettings> </caching> |
In CacheProfile, pass the Profile name available in web.config.
In this example, we have 2 Cache Profile – LongDuration and ShortDuration
[OutputCache (CacheProfile = “CacheProfile1”)] public ActionResult Index() { ViewBag.CurrTime = DateTime.Now.ToString(); return View(); } |
Benefit of Using CacheProfile in ASP.Net MVC –
We can manage the Cache duration from web.config file itself.
You may use varByParam parameter to use cache based on a specific parameter.
Remember, you should cached only those data which are common for all users of your website.
Hope you like this blog.
You may like other blogs on ASP.Net MVC –