Caching in MVC

Different types of Caching Part 1

Why caching needed?

  • If many user are trying to accessing the site, it means your server has so many requests by the user, If every request hit the server for the response then it will lead to performance issues.
  • For example,if a page may contain some static information in your web site, in this scenario we can cache those content and don’t force your server to get them from data base in every request.This will increase your perfomance.

Advantage of Caching

  • Reduce Database and hosting server round-trips
  • Reduce network traffic
  • Improve performance

Remember while using Cache :

  • While caching of dynamic contents that change frequently, set minimum cache–expiration time.
  • Avoid caching for contents that are not accessing frequently.

Output Cache Filter :

It’s used to cache the data that is output of an action method.In default, this will cache the data upto 60 seconds.After 60 seconds, Asp.Net MVC will execute the action method again and start caching the output again.

Let we see with example..

Controller :

public class OutputCachingController : Controller
[OutputCache(Duration = 20, VaryByParam = “none”)]
public ActionResult Index()
ViewBag.CurrentDateTime = DateTime.Now.ToString();
return View();

View :

@{  ViewBag.Title = “Index”;}

Run the application, first time it will show the output like below


up to 20 seconds it will show the same time in the browser without changing after we refresh the page because it will not call the action method upto 20 seconds ( so no new time updated in the viewbag)

VaryByParam : This property enables you to create different cached versions of the content when a form parameter or query string parameter varies.

VaryByParam = “aadharsh”

If it find records matching “aadharsh” string then a cache will be created,if paremeter/querystring changes than it will replace the old one with new

Let we discuss about Donut caching and Donut Hole caching in Part 2