Improving performance with Output Caching in ASP.net MVC application

 

Goal: Here, I am going to explain, how we can improve performance of ASP.Net MVC application using output caching.

Advantage

  1. It enables us to cache the content returned by Controller action.
  2. It stops controller action to generate same content each time.
  3. We can set caching parameter using output cache.
  4. We can specify where to send caching data. For example web Server or user browser etc
  5. Caching enables us to avoid performing redundant work at server.

 How it helps?Imagine, for example, that our ASP.NET MVC application displays a list of database records in a view named Display. Normally, each and every time that a user invokes the controller action that returns the Display view, the set of database records must be retrieved from the database by executing a database query.

If, on the other hand, we take advantage of the output cache then we can avoid executing a database query every time any user invokes the same controller action. The view can be retrieved from the cache instead of being regenerated from the controller action.

How to enable Output Caching?

namespace SampleMVC1.Controllers

{
public class customController:Controller
{

[OutputCache (Duration=20, VaryByParam="None" )]

public ActionResult display()
{
//Response.redirect();
// ViewData["Message"] = “Welcome to Dhananjay!”;
return Content(“I will Kill you MVC”);
//return View();
}}
}

Here, we are enabling Output cache for a controller named customController. In above listing output of display action will be cached for 20 seconds. In above code, we are enabling output cache for display action of customController controller. If we want to enable output caching for entire controller (display), then, we will have to write code as follows

namespace SampleMVC1.Controllers{

[OutputCache(Duration = 20, VaryByParam = "None")]
public class customController:Controller
{
// [OutputCache (Duration=20, VaryByParam="None" )]
public ActionResult display()
{
//Response.redirect();
// ViewData["Message"] = “Welcome to Dhananjay!”;
return Content(“I will Kill you MVC”);
//return View();
}}
}
How to calculate caching duration?
If we want to cache output of controller action for one day then parameter to duration would be calculated as 60 sec * 60 Min * 24 hrs = 86400 seconds.

[OutputCache(Duration = 86400, VaryByParam = "None")]

Where Content is Cached

By default, when we use the [OutputCache] attribute, content is cached in three locations:

  1. the web server
  2. any proxy servers
  3. the web browser.

We can control exactly where content is cached by modifying the Location property of the [OutputCache] attribute.


We can set the Location property to any one of the following values:

· Any

· Client
· Downstream

· Server

· None

· ServerAndClient

By default, the Location property has the value Any. However, there are situations in which you might want to cache only on the browser or only on the server. For example, if we are caching information that is personalized for each user then we should not cache the information on the server. If we are displaying different information to different users then we should cache the information only on the client.

How to create a cache profile?

Cache profile could be created in Web.config file. Creating cache profile in Web.config having many advantages, like

  1. We can store controller action cache in one central location.
  2. We can create one cache profile and apply the profile to several controllers or controller actions.
  3. We can modify Web.config file without recompiling the application. 

    Cache profile in Web.config file.

 


<
caching>

<outputCacheSetting>

<outputCacheProfile><addname=CacheHourduration=3600 /> </outputCacheProfile>
</outputCacheSetting>
</caching>

 How to apply cache profile in Controller action?

[OutputCache(CacheProfile="Cache1Hour")]

public string Index()

{

return DateTime.Now.ToString(“T”);

}

Caching Example

This caching example will display same time for 10 seconds

Home\Index.Cs

using System.Web.Mvc;

 namespace MvcApplication1.Controllers

{

[HandleError]

public class HomeController : Controller

{

[OutputCache(Duration=10, VaryByParam="none")]

public ActionResult Index()

{

return View();

}

 }

}

View\Index.CS

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Index.aspx.cs” Inherits=”MvcApplication1.Views.Home.Index” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >

<head runat=”server”>

<title>Index</title>

</head>

<body>

<div>

The current time is: <%= DateTime.Now.ToString(“T”) %>

</div>

</body> </html>

Happy Coding

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s