OutputCache Action Filter In ASP.NET MVC

In this article, we will learn how to use OutputCache Action Filter in ASP.NET MVC Applications. In previous ASP.NET MVC tutorials of this series, we saw
One of the best ways to improve the performance of an ASP.NET MVC Application is by caching. With the help of caching, we can reduce hosting and the database Server round trips. We can apply Outputcache Action Filter either on Action Method or on the controller. OutputCache attribute has several properties like CacheProfile, Duration, Location, VaryByParam, VaryByHeader, NoStore etc.

Let’s create a simple example, so that we can understand OutputCache attribute better.
Let’s begin

Create a new ASP.NET MVC Application.


Select Empty MVC Application and click OK.

For this example, I have created a database (named as DemoDB) with a table (Employee) having schema, as shown below. (I will use Entity Framework with Database First approach. In this example, you can use any with which you feel comfortable).
  1. CREATE TABLE dbo.Employee  
  2.     (  
  4.     Name NVARCHAR (100) NULL,  
  5.     City NVARCHAR (100) NULL,  
  6.     CONSTRAINT PK_Employee PRIMARY KEY (ID)  
  7.     )  
  8. GO  
Right click on Models and then click on Add new item. Select ADO.NET Entity Data Model. Give it a meaningful name and click Add.

Select EF Designer from the database and click next.

Create New Connection and select version of Entity framework, which you want to use.


Select the database objects which you want to add in your model and click finish.


Afterwards, you will see Employee Entity in Designer.


Now, right click on the controller and add Empty controller.


Bind the employee data to the view.
  1. public ActionResult Index()  
  2. {  
  3.     DemoDBEntities db = new DemoDBEntities();  
  4.     var Employees = db.Employees.ToList();  
  5.     return View(Employees);  
  6. }  
Index.cshtml code
  1. @model IEnumerable<OutputCacheApplication.Models.Employee>  
  3. @{  
  4.     Layout = null;  
  5. }  
  7. <!DOCTYPE html>  
  9. <html>  
  10. <head>  
  11.     <meta name="viewport" content="width=device-width" />  
  12.     <title>Index</title>  
  13.     <script src="~/Scripts/jquery-1.9.1.min.js"></script>  
  14.     <script src="~/Scripts/bootstrap.min.js"></script>  
  15.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  16. </head>  
  17. <body>  
  18.     <div class="container">  
  19.         <div class="row">  
  20.             <div>  
  21.                 <div class="alert alert-info"><b>Data Collected @@ @DateTime.Now.ToString()</b></div>  
  22.             </div>  
  23.         </div>  
  24.         <div class="row">  
  25.             <div>  
  26.                 <table class="table table-striped">  
  27.                     @foreach (var item in Model)  
  28.                     {  
  29.                         <tr><td>@item.ID</td><td>@item.Name</td><td>@item.City</td></tr>  
  30.                     }  
  31.                 </table>  
  32.             </div>  
  33.         </div>  
  34.     </div>  
  35. </body>  
  36. </html>  
Build and run the Application. Whenever we refresh the page, GET request is sent to the Index Action of Home Controller.

Let’s add Output cache action filter on Index action method. 
  1. [OutputCache(Duration = 10, VaryByParam = "none")]  
  2. public ActionResult Index()  
  3. {  
  4.         DemoDBEntities db = new DemoDBEntities();  
  5.         var Employees = db.Employees.ToList();  
  6.         return View(Employees);  
  7. }  
Here, we set the duration to 10 sec, which means cached ActionResult/output will be expired after 10 seconds. Now, build and run the Application.

If the memory resources are lower than ASP.NET, clears the items from the cache before completing its duration/Expiry time.
Example of OutputCache with Location property

By using the Location property of output cache, we can control, where the output is cached. For example, if we want to cache some personal information, then it is recommended to catch it on the client. If the output data is private/confidential, it is recommended not to store it in cache.
  1. [OutputCache(Duration = 10, VaryByParam = "none", Location = System.Web.UI.OutputCacheLocation.Client)]  
  2. public ActionResult Index()  
  3. {  
  4.       DemoDBEntities db = new DemoDBEntities();  
  5.       var Employees = db.Employees.ToList();  
  6.       return View(Employees);  
  7. }  
OutputCache filter adds an appropriate cache control header in response, which is based upon Location property.

Example of OutputCache with VaryByParam attribute

VaryByParam property creates a different cache, which is based upon the parameter value and is passed through Query String or Request.Form.
  1. [OutputCache(Duration =20,VaryByParam ="ID")]  
  2. public ActionResult SearchRecord(int ID)  
  3. {  
  4.       DemoDBEntities db = new DemoDBEntities();  
  5.       var Employees = db.Employees.Where(x=>x.ID==ID).ToList();  
  6.       return View("Index", Employees);  
  7. }  

Example of OutputCache with CacheProfile
If we want to have same type of OutputCache properties on multiple Action method or multiple controller, then we can use CacheProfile property. CacheProfile has several advantages. For example, we can change OutputCache property at multiple places from one central location and will apply without recompiling our Application. Add Caching section in system.web section, which will contain OutputCacheSettngs. In OutputCacheSettngs, we have added outputCacheProfiles with the name and other properties.
  1. <caching>  
  2.       <outputCacheSettings>  
  3.         <outputCacheProfiles>  
  4.           <add name="CacheFor20Seconds" duration="20" varyByParam="none" location="Server"/>  
  5.         </outputCacheProfiles>  
  6.       </outputCacheSettings>  
  7. </caching>  
Now, go to your Action method or controller and add CacheProfile property in OutputCache Action Filter.
  1. [OutputCache(CacheProfile = "CacheFor20Seconds")]  
  2. public ActionResult WorkingWithCacheProfile()  
  3. {  
  4.     DemoDBEntities db = new DemoDBEntities();  
  5.     var Employees = db.Employees.ToList();  
  6.     return View("Index",Employees);  
  7. }  

Up Next
    Ebook Download
    View all
    View all