ARTICLE

Output caching in ASP.NET MVC application

Posted by Dhananjay Kumar Articles | ASP.NET MVC with C# February 22, 2009
This article will explain how we could cache output in an MVC web application. The article also discusses the advantages of caching in an MVC Framework application.
Reader Level:

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>
          <
add name="CacheHour"  duration="3600" />
         </outputCacheProfile>
      </
outputCacheSetting>
      </
caching>


How to apply cache profile in Controller action?

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

        public ActionResult Index()

        {

            return View();

        }


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">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">

    <title>Index</title>

</head>

<body>

    <div>

   

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

   

        </div>

</body> </html>


Login to add your contents and source code to this article
post comment
     

cache in asp.net is stand alone and in process in nature thats why we cant used it in a larger web garden. it happens because of the fact that data is distributed over multiple severs in a web garden so an in-process and stand alone cache is incompetent is these situations. in other words asp.net cache is a good tool to use only in smaller web farms for the performance and scalability of the app. in order to achieve the same results in a larger web garden where number of servers are more then two, the use of a distributed cache like App fabric or NCache (http://www.alachisoft.com/ncache/index.html) can be a good option .

Posted by james lee Feb 23, 2011

nice.  thanks

Posted by Ross McLoughlin Jul 16, 2010
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts