Define cache profile in MVC.

Please explain to me briefly about the cache profile within MVC with example.

Last updated:2/11/2020 1:13:37 AM

1 Answers

Nishi Tiwari
Nishi Tiwari

We can create a cache profile in the web.config file and it is an alternative to configuring output cache properties by modifying properties of the [OutputCache] attribute. It also offers a couple of important advantages which are as follows.

  •  It Controls how controller actions cache content in one central location.
  •  It creates one cache profile and applies the profile to several controllers or controller actions.
  •  It modifies the web configuration file without recompiling your application.
  •  It disables caching for the application that has already been deployed to production.

First, take a look at a simple example of a cache profile by creating the cache profile on web.config file. These <caching> section must appear within the <system.web> section.

<caching>

   <outputCacheSettings>
      <outputCacheProfiles>
         <add name = 'Cache10Min' duration = '600' varyByParam = 'none'/>
      </outputCacheProfiles>
   </outputCacheSettings>
</caching>

We can apply the Cache10Min profile to a controller action with the [OutputCache] attribute which is as follows.

[OutputCache(CacheProfile = 'Cache10Min')]

public ActionResult Index(){ 
   var employees = from e in db.Employees
   orderby e.ID
   select e;
   return View(employees);
}

Run the application and specify the following URL http://localhost:63004/employee

Define cache profile in MVC.

If we invoke the Index() action as shown above then the same time will be returned for 10 Min.

Answer