Caching
Caching is used to improve the performance in ASP.NET MVC. Caching is a technique which stores something in memory that is being used frequently to provide better performance. In ASP.NET MVC, OutputCache attribute is used for applying Caching. OutputCheching will store the output of a Controller in memory and if any other request comes for the same, it will return it from cache result.
OutputCache attribute can have a parameter.
Duration
It describes the time in seconds.
The example of duration is given below.
- [OutputCache(Duration = 60)]
- public ActionResult Index() {
- var emps = from e in db.Employees
- orderby e.ID
- select e;
- return View(emps);
- }
It describes cache will be stored on the basis of a parameter. Cache will be stored on the basis of the list of semicolon separated by a string.
The example of VaryByParam is given below.
- [OutputCache(Duration = 60, VaryByParam = "Id")]
- public ActionResult Index(int Id) {
- var emps = from e in db.Employees where e.DeptID = Id
- orderby e.ID
- select e;
- return View(emps);
- }
It specifies where the cache is stored. Below is options available for locations
- Any (Default)- Content is cached in three locations- the Web Server, any proxy Servers and the Web Browser.
- Client- Content is cached on the Web Browser.
- Server- Content is cached on the Web Server.
- ServerAndClient- Content is cached on the Web Server and the Web Browser.
- None- Content is not cached anywhere.
- [OutputCache(Duration = 60, VaryByParam = "Id", , Location = OutputCacheLocation.Client)]
- public ActionResult Index(int Id) {
- var emps = from e in db.Employees where e.DeptID = Id
- orderby e.ID
- select e;
- return View(emps);
- }
CacheProfile
CacheProfile is another way to handle cache. You can create profiles in web.config.
The example is given below.
In web.config
- <caching>
- <outputCacheSettings>
- <outputCacheProfiles>
- <add name="Long" duration="60" varyByParam="Id" />
- <add name="Medium" duration="60" varyByParam="none" />
- <add name="Short" duration="10" varyByParam="none" /> </outputCacheProfiles>
- </outputCacheSettings>
- </caching>
In Controller
- [OutputCache(CacheProfile = "Long")]
- public ActionResult Index(int Id) {
- var emps = from e in db.Employees where e.DeptID = Id
- orderby e.ID
- select e;
- return View(emps);
- }

Deepmala WakadePosted Nov 18, 2021, 6:24 AM
Gone through lot of blogs but this given me perfect idea of Cache.
Rocky RoyalsonPosted May 24, 2018, 10:47 AM
Well explained Pradeep, thanks for sharing!!!!!! :)
Asif IqbalPosted Nov 30, 2017, 6:18 AM
What is the default Duration of output cache?
Former memberPosted May 30, 2017, 7:05 AM
If i want to cache action by two parameter instead of one the what will be the code look like ? what is the meaning of varyByParam="none" ?