Three Ways To Improve Performance Using Caching In ASP.NET MVC Applications

Nowadays, visiting a website on a desktop or on mobile is our daily routine. Whenever we visit a website or a web application, then we expect that it will render very soon, within 5 to 10 seconds. But unfortunately, there are only a very few websites that take the minimum time to open and the reasons behind this are as following.

  1. Huge content
  2. Large and multiple images
  3. Complex business logic
  4. Too much server requests
  5. Poor connection
  6. Data Access Layer etc.

So, there are several reasons behind the slowness of a website. Now, what we can do to resolve these issues that hamper the performance of the website is, we can use Caching. Yes, using caching, we can cache the data and if the user makes another request for the same type of data, then we don’t need to go and get the same data again from the Server and we don’t need to execute the same logic again and again.

Caching is a technique which helps us to store our data somewhere we already have, and if we require the same data again, then we can get it from the stored data. Data can be saved at client side as well as server side. It totally depends on your requirements, not your choice.

Advantage of caching

If we define the advantage of caching in one word, that will be “Performance”; and it can be achieved to minimize the following things.

  1. Minimize Server round trips [Hosting Server or Database Server or Any Other Server]
  2. Minimize Network Traffic [Http Call to Server]
  3. Avoid repeating same data binding logic

Tips and Tricks when using ASP.NET MVC caching

  1. Don’t use caching with the data which changes frequently.
  2. Don’t use caching with Authentication logic.
  3. Don’t use caching with the data which is unique for the individual user.
  4. Don’t use caching with data which use very rare like privacy policy page.
  5. Don’t use caching for an Error page.
  6. Use caching with data which is used very frequently and same data can be used by all user.
  7. Always use caching with images or media files.

Generally, we can cache our data using 3 ways in ASP.NET MVC.

  1. Caching Static Content
  2. Caching whole or partial page response using OutputCache Attribute
  3. Caching shared data

CACHING STATIC CONTENTS

While designing any website, we have to use static content. Static Content generally means a piece of content that does not change dynamically, like your images, CSS and JavaScript files etc. These are really heavy files and loading these from the server is a time-consuming task. Do you know how much time is taken to load this static content? It is probably more than 60% of the total time we are consuming. But that is normal. If we use more static content, then it will definitely take more time to load.

Now, the question arises, "Should it take time to download this content every time when we use the same page on the same browser again and again?" 

Well, the answer is NO. The downloading process should be the part of the first time, not everytime. So, what we can do is to use Static Content Caching in ASP.NET MVC here to cache our downloaded static contents in memory and when we access the same page again, then rather than going to download the whole static contents again from the server, we just get these from the memory caches.

Let's understand it from a demonstration of how we can achieve static contents caching in ASP.NET MVC. 

Here, I have created one ASP.NET MVC 4 application. If you don't know how to create Asp.Net MVC application, just follow my previous articles. After creating an application, go to Index View for the HomeController which is auto-generated using the following codes. Here, you can see that I have just added three images. For this demonstration, I have downloaded these images from Google; you can test it with any images. So, when we run the application, these images will be downloaded from the server every time.

  1. @{  
  2.     ViewBag.Title = "Home Page";  
  3. }  
  4. <style>  
  5.     table td {  
  6.         padding: 10px;  
  7.         border: 2px solid #808080;  
  8.         text-align: center;  
  9.     }  
  10. </style>  
  11. <div class="jumbotron">  
  12.     <h3>Static Content Caching in Asp.Net MVC</h3>  
  13.     <table>  
  14.         <tr>  
  15.             <td><img src="~/Content/img/image1.png" width="300" height="300" />Image 1</td>  
  16.             <td><img src="~/Content/img/image2.jpg" width="300" height="300" />Image 2</td>  
  17.             <td><img src="~/Content/img/image3.png" width="300" height="300" />Image 3</td>  
  18.         </tr>  
  19.     </table>  
  20. </div>  

Here is the Index Action method which is responsible for rendering our Index View. 

  1. //Static content caching  
  2. public ActionResult Index()  
  3. {  
  4.     return View();  
  5. }  

Now, it's time to run the application and see what happens. When we run the application and go to developer tools > Networks section, we find that each static content like images, CSS or JS file is being downloaded. But if we refresh the same page, again the same process repeats and same files are downloaded again.

Caching In ASP.NET

To cache static contents, we have to define a few configurations in our application's Web.Config file as below. Here, you can see, we have defined the file extension with mime type which needs to be cache. To define an age of caching time, we use "cacheControlMaxAge" attribute from "clientCache" and define the time here. For this demonstration, we have used 1 minute.

  1. <system.webServer>  
  2.     <staticContent>  
  3.       <clear/>  
  4.       <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:01:00" />  
  5.       <mimeMap fileExtension=".jpg" mimeType="image/jpg"/>  
  6.       <mimeMap fileExtension=".png" mimeType="image/jpg"/>  
  7.       <mimeMap fileExtension=".css" mimeType="text/css"/>  
  8.       <mimeMap fileExtension=".js" mimeType="text/javascript"/>  
  9.     </staticContent>  
  10.     <validation validateIntegratedModeConfiguration="false" />  
  11.     <modules>  
  12.       <remove name="ApplicationInsightsWebTracking" />  
  13.       <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />  
  14.     </modules>  
  15. </system.webServer>  

Again, it is time to run the application after configuration of caching for static contents.  When we run the application for the first time, we see the same screen as above where we will find that each component is being downloaded in a specific time. But if we run the application again within 1 minute, we will see the output as follows. 

The following images show that each static component is being retrieved from memory cache rather than downloaded from the server. So, here, we have achieved static caching technique. Now, using this, we can cache static contents and we don't need to download these every time.

Caching In ASP.NET

OUTPUT CACHING

In ASP.NET MVC, we can cache page response using "OutputCache" attribute. This type of caching is basically used to cache your content generated by an action method. "OutputCache" attribute can be used with activity level or controller level. In Output Caching, we can define the age of caching using duration in seconds. Here, we can also define the location for caching; it can be client side or server side. If we would like to cache the content using some parameter, then it can be defined using "VaryByParam".

So, let us understand it with an example. Now, we will create a new action method as "Index1" as follows. Here, we are creating a list for the blog post which contains 1000 records. 

  1. //Output caching  
  2. [OutputCache(Duration = 60, VaryByParam = "none", Location = System.Web.UI.OutputCacheLocation.Server)]  
  3. public ActionResult Index1()  
  4. {  
  5.  var postModel = new List < BlogPost > ();  
  6.   
  7.  //Suppose getting blog post data form API call.    
  8.  for (int i = 0; i < 1000; i++) {  
  9.   postModel.Add(new BlogPost() {  
  10.    PostId = i, Title = "Blog Post Title " + i, Category = "Category " + i, Content = "Content for Blog Post " + i  
  11.   });  
  12.  }  
  13.   
  14. foreach(var item in postModel)   
  15. {  
  16.   if (item.PostId % 2 == 0) {  
  17.    item.UserName = "Mukesh Kumar";  
  18.   } else {  
  19.    item.UserName = "Admin";  
  20.   }  
  21.  }  
  22.   
  23.   
  24.  return View(postModel);  
  25. }  

Following is the entity class "BlogPost" for Blog.

  1. namespace CachingInMVC.Models  
  2. {  
  3.     public class BlogPost  
  4.     {  
  5.         public int PostId { get; set; }  
  6.         public string Title { get; set; }  
  7.         public string Category { get; set; }  
  8.         public string Content { get; set; }  
  9.         public string UserName { get; set; }  
  10.     }  
  11. }  

Now, we need to create a view "Index1" inside the Home folder of the View. This View basically renders all the blog posts in tabular view. We have defined date time to see when our data last updated. 

  1. @model IEnumerable<CachingInMVC.Models.BlogPost>  
  2. @{  
  3.     ViewBag.Title = "Home Page";  
  4. }  
  5. <style>  
  6.     table td {  
  7.         padding: 10px;  
  8.         border: 2px solid #808080;  
  9.         text-align: center;  
  10.     }  
  11. </style>  
  12. <div class="jumbotron">  
  13.     <h2>Output Caching in Asp.Net MVC</h2>  
  14.     <h3>Last Update Data: <strong style="color:red;">@DateTime.Now.ToString()</strong></h3>  
  15.     <br />  
  16.     <table style="border:3px solid #808080;">  
  17.         <tr>  
  18.             <th>ID</th>  
  19.             <th>Title</th>  
  20.             <th>Category</th>  
  21.             <th>Content</th>  
  22.             <th>User</th>  
  23.         </tr>  
  24.         @foreach (var post in Model)  
  25.         {  
  26.             <tr style="border:1px solid #808080">  
  27.                 <td>@post.PostId</td>  
  28.                 <td>@post.Title</td>  
  29.                 <td>@post.Category</td>  
  30.                 <td>@post.Content</td>  
  31.                 <td>@post.UserName</td>  
  32.             </tr>  
  33.         }  
  34.     </table>  
  35. </div>  

When we run the application, we will find the output as below where we can see the time forthe  last updated data along with the blog post data in tabular format. As above with action method, we are using Output Caching with a duration of 60 seconds. So, if we reload this page again within 60 seconds, then it will not process the whole code for "Index1" and render the data from the cache.

Caching In ASP.NET

Here, we have reloaded the page again. The page rendered very quickly and we can see, the data is same as the previous result and the time for the last updated data is the same because everything is being retrieved from the server rather than executing the whole code again for "Index1".

Caching In ASP.NET

COMMON DATA CACHING 

Now, if we are required to share common data with multiple action methods and would like to add this type of data in the cache, then we can use "HttpContext.Cache" for setting or getting the data. As we can see with the below code, we are just using the same code which we have already used with the Output Cache example above but here we have removed model data, creating logic inside a method.

At first, we will try to check if the data is available in Cache using the defined key, if data is there then we will render the data on view from the cache and if not then we will get the data from "getThousandsPost" method and bind the model. But make sure, before rendering the data, that we add this data inside the cache so that the next time we don't need to go and execute the same logic again and again.

Getting the data from the cache.

  1. var postModel = HttpContext.Cache.Get("ThousandsPost") as List < BlogPost > ;  

Setting the data in the cache.

  1. HttpContext.Cache.Insert("ThousandsPost", postModel, null, DateTime.Now.AddMinutes(1), Cache.NoSlidingExpiration);  
  2.    
  3. //Common data caching  
  4. public ActionResult Index2()   
  5. {  
  6.  var postModel = HttpContext.Cache.Get("ThousandsPost") as List < BlogPost > ;  
  7.    
  8.  if (postModel == null) {  
  9.   postModel = this.getThousandsPost();  
  10.   HttpContext.Cache.Insert("ThousandsPost", postModel, null, DateTime.Now.AddMinutes(1), Cache.NoSlidingExpiration);  
  11.  }  
  12.   
  13.  return View(postModel);  
  14. }  
  15.   
  16. private List < BlogPost > getThousandsPost()   
  17. {  
  18.  List < BlogPost > post = new List < BlogPost > ();  
  19.   
  20.  //Suppose getting blog post data form API call.    
  21.  for (int i = 0; i < 1000; i++)   
  22.  {  
  23.   post.Add(new BlogPost() {  
  24.    PostId = i, Title = "Blog Post Title " + i, Category = "Category " + i, Content = "Content for Blog Post " + i  
  25.   });  
  26.  }  
  27.   
  28.  foreach(var item in post)   
  29.  {  
  30.   if (item.PostId % 2 == 0) {  
  31.    item.UserName = "Mukesh Kumar";  
  32.   } else {  
  33.    item.UserName = "Admin";  
  34.   }  
  35.  }  
  36.  return post;  
  37. }  

Here using the new view "Index2" as follows.

  1. @model IEnumerable<CachingInMVC.Models.BlogPost>  
  2. @{  
  3.     ViewBag.Title = "Home Page";  
  4. }  
  5. <style>  
  6.     table td {  
  7.         padding: 10px;  
  8.         border: 2px solid #808080;  
  9.         text-align: center;  
  10.     }  
  11. </style>  
  12. <div class="jumbotron">  
  13.   
  14.     <h2>Data Caching in Asp.Net MVC</h2>  
  15.     <h3>Last Update Data: <strong style="color:red;">@DateTime.Now.ToString()</strong></h3>  
  16.     <br />  
  17.     <table style="border:3px solid #808080;">  
  18.         <tr>  
  19.             <th>ID</th>  
  20.             <th>Title</th>  
  21.             <th>Category</th>  
  22.             <th>Content</th>  
  23.             <th>User</th>  
  24.         </tr>  
  25.         @foreach (var post in Model)  
  26.         {  
  27.             <tr style="border:1px solid #808080">  
  28.                 <td>@post.PostId</td>  
  29.                 <td>@post.Title</td>  
  30.                 <td>@post.Category</td>  
  31.                 <td>@post.Content</td>  
  32.                 <td>@post.UserName</td>  
  33.             </tr>  
  34.         }  
  35.     </table>  
  36. </div>  

When we run the application, we will notice that our date time is being changed every time. It is because date time is not a part of the cache. We have defined it in the View. To check if the data is loading from cache or not, just put a breakpoint in the "getThousandsPost()" method. You will find that the first time we hit this method and once the data is cached, we will get data from cache next time.

Caching In ASP.NET

Conclusion

So, today, we learned how to cache our data in ASP.NET MVC. The data can be of any type, it could be static content or page response or common data which needs to be shared.

I hope, this post will help you. Please put your feedback into the comments section which will help me to improve myself for the next post. If you have any doubts, please ask; and if you like this post, please share it with your friends.


Similar Articles