OutputCache In ASP.NET MVC

Introduction

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 the database server round trips. We can apply OutputCache Action Filter either on Action Method or on the controller. The OutputCache attribute is used to cache the content returned by a controller action method, so that, the same content does not need to be generated each and every time the same controller action is invoked.

OutputCache attribute has several properties.

  • CacheProfile
  • Duration
  • Location
  • VaryByParam
  • VaryByHeader
  • NoStore

Why do we need Caching?

We need caching in many different scenarios to improve the performance of an application. For example, if we have an ASP.NET MVC application, which displays a list of employees. Now, when these records are retrieved from the database by executing a database query, each and every time a user invokes the controller action, it returns the Index view.

We can take advantage of the output cache to avoid executing a database query every time a user invokes the same controller action. In this case, the view will be retrieved from the cache instead of being regenerated from the controller action.

Step 1

Open Visual Studio 2015 or your choice and create a new project.

Step 2

Choose the web application project and give an appropriate name to your project.
 
OutputCache In ASP.NET MVC 

Step 3

Select the empty template, check on MVC checkbox below, and click OK.
 
OutputCache In ASP.NET MVC 

Step 4

Right-click on the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select New Item.
 
OutputCache In ASP.NET MVC 

You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add".

OutputCache In ASP.NET MVC 

After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".

OutputCache In ASP.NET MVC 

After clicking on "Next", a window will appear. Choose "New Connection". Another window will appear. Add your server name - if it is local, then enter a dot (.). Choose your database and click "OK".

OutputCache In ASP.NET MVC 

The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next",

OutputCache In ASP.NET MVC
 
OutputCache In ASP.NET MVC 

After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".

Entity Framework gets added and the respective class gets generated under the Models folder.

OutputCache In ASP.NET MVC 

Step 5

Right click on controllers folder add controller.
 
OutputCache In ASP.NET MVC 

A window will appear. Choose MVC5 Controller-Empty and click "Add".

OutputCache In ASP.NET MVC 

After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home;

OutputCache In ASP.NET MVC 

Complete code for Home Controller

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. using MvcFilters_Demo.Models;  
  8.    
  9. namespace MvcFilters_Demo.Controllers  
  10. {  
  11.     public class HomeController : Controller  
  12.     {  
  13.         private readonly EmployeeContext _dbContext =new EmployeeContext();  
  14.    
  15.         //[OutputCache(Duration = 15, VaryByParam ="none",Location = System.Web.UI.OutputCacheLocation.Client)]  
  16.         [OutputCache(CacheProfile = "1MinutCatche")]  
  17.         public ActionResult Index()  
  18.         {  
  19.             System.Threading.Thread.Sleep(3000);  
  20.             var employee = _dbContext.Employees.ToList();  
  21.             return View(employee);  
  22.         }  
  23.    
  24.         [OutputCache(Duration = int.MaxValue, VaryByParam = "id")]  
  25.         public ActionResult Details(int? id)  
  26.         {  
  27.             if (id == null)  
  28.             {  
  29.                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  30.             }  
  31.             var employee = _dbContext.Employees.Find(id);  
  32.             if (employee==null)  
  33.             {  
  34.                 return HttpNotFound();  
  35.             }  
  36.    
  37.             return View(employee);  
  38.         }  
  39.     }  
  40. }  

Step 6

Right click on Index method in HomeController The "Add View" window will appear with default index name checked (use a Layout page), and click on "Add.

 

OutputCache In ASP.NET MVC

 

  1. @using System.Globalization  
  2. @model IEnumerable<MvcFilters_Demo.Models.Employee>  
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.    
  7. <h2>List of Employee</h2>  
  8. <b>Employee List retrieved @@ @DateTime.Now.ToString(CultureInfo.CurrentCulture)</b>  
  9.    
  10. <table class="table table-bordered">  
  11.     <thead>  
  12.     <tr>  
  13.         <th>@Html.DisplayNameFor(m=>m.Name)</th>  
  14.         <th>@Html.DisplayNameFor(m=>m.Gender)</th>  
  15.         <th>@Html.DisplayNameFor(m=>m.Age)</th>  
  16.         <th>@Html.DisplayNameFor(m=>m.Position)</th>  
  17.         <th>@Html.DisplayNameFor(m=>m.Office)</th>  
  18.         <th>@Html.DisplayNameFor(m=>m.HireDate)</th>  
  19.         <th>@Html.DisplayNameFor(m=>m.Salary)</th>  
  20.         <th>Action(s)</th>  
  21.     </tr>  
  22.     </thead>  
  23.     <tbody>  
  24.     @foreach (var emp in Model)  
  25.     {  
  26.         <tr>  
  27.             <td>@emp.Name</td>  
  28.             <td>@emp.Gender</td>  
  29.             <td>@emp.Age</td>  
  30.             <td>@emp.Position</td>  
  31.             <td>@emp.Office</td>  
  32.             <td>@emp.HireDate</td>  
  33.             <td>@emp.Salary</td>  
  34.             <td>@Html.ActionLink("Details","Details",new {id=emp.EmployeeId})</td>  
  35.         </tr>  
  36.     }  
  37.     </tbody>  
  38. </table>  

Step 7

Right click on Details method in HomeController. The "Add View" window will appear with default Details name checked (use a Layout page), and click on "Add.
 
OutputCache In ASP.NET MVC 

Code for details view

  1. @model MvcFilters_Demo.Models.Employee  
  2. @{  
  3.     ViewBag.Title = "Details";  
  4. }  
  5.    
  6. <h2>Employee Details</h2>  
  7. <dl class="dl-horizontal">  
  8.     <dt>@Html.DisplayNameFor(m => m.Name)</dt>  
  9.     <dd>@Html.DisplayFor(m => m.Name)</dd>  
  10.     <dt>@Html.DisplayNameFor(m => m.Gender)</dt>  
  11.     <dd>@Html.DisplayFor(m => m.Gender)</dd>  
  12.     <dt>@Html.DisplayNameFor(m => m.Age)</dt>  
  13.     <dd>@Html.DisplayFor(m => m.Age)</dd>  
  14.     <dt>@Html.DisplayNameFor(m => m.Position)</dt>  
  15.     <dd>@Html.DisplayFor(m => m.Position)</dd>  
  16.     <dt>@Html.DisplayNameFor(m => m.Office)</dt>  
  17.     <dd>@Html.DisplayFor(m => m.Office)</dd>  
  18.     <dt>@Html.DisplayNameFor(m => m.HireDate)</dt>  
  19.     <dd>@Html.DisplayFor(m => m.HireDate)</dd>  
  20.     <dt>@Html.DisplayNameFor(m => m.Salary)</dt>  
  21.     <dd>@Html.DisplayFor(m => m.Salary)</dd>  
  22. </dl>  

OutputCache

  1. [OutputCache(Duration = 15)]  
  2.        public ActionResult Index()  
  3.        {  
  4.            System.Threading.Thread.Sleep(3000);  
  5.            var employee = _dbContext.Employees.ToList();  
  6.            return View(employee);  
  7.        }  
OutputCache with Location property
  1. [OutputCache(Duration = 15, VaryByParam ="none",Location = System.Web.UI.OutputCacheLocation.Client)]  
  2.         public ActionResult Index()  
  3.         {  
  4.             System.Threading.Thread.Sleep(3000);  
  5.             var employee = _dbContext.Employees.ToList();  
  6.             return View(employee);  
  7.         }  
  8.    
  9.         [OutputCache(Duration = int.MaxValue, VaryByParam = "id")]  
  10.         public ActionResult Details(int? id)  
  11.         {  
  12.             if (id == null)  
  13.             {  
  14.                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  15.             }  
  16.             var employee = _dbContext.Employees.Find(id);  
  17.             if (employee==null)  
  18.             {  
  19.                 return HttpNotFound();  
  20.             }  
  21.    
  22.             return View(employee);  
  23.         }  
CacheProfiles
  1.  <caching>  
  2.       <outputCacheSettings>  
  3.         <outputCacheProfiles>  
  4.           <clear/>  
  5.           <add name="1MinutCatche" duration="60" varyByParam="none"/>  
  6.         </outputCacheProfiles>  
  7.       </outputCacheSettings>  
  8.     </caching>  
  9.   
  10. [OutputCache(CacheProfile = "1MinutCatche")]  
  11.        public ActionResult Index()  
  12.        {  
  13.            System.Threading.Thread.Sleep(3000);  
  14.            var employee = _dbContext.Employees.ToList();  
  15.            return View(employee);  

Step 8

Built and run your project by ctrl and F5.
 
OutputCache In ASP.NET MVC


Similar Articles