Caching in ASP.Net MVC

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();
        }

This will cached the Action method result for subsequent requests upto 120 seconds.

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>
          <add name="CacheProfile1" duration="120" varyByParam="none" />
          <add name="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();
        }

You can create multiple CacheProfile based on your requirement.
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.
For eg  A product description will be common for all users.
Sometimes we should not cached a particular data at server. 
For eg - Location or City Or Country should not be cached at the server side as this will different for other users.
 Hope you like this blog.

You may like other blogs on ASP.Net MVC -

Comments

Popular