Click here to Skip to main content
15,882,209 members
Articles / Web Development / ASP.NET

A Beginner's Tutorial on Caching in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.83/5 (32 votes)
22 Feb 2012CPOL7 min read 118.5K   1.7K   59   14
This article is a beginner's tutorial on ASP.NET caching mechanism.


This article is a beginner's tutorial on ASP.NET caching mechanism. We will try to see different types of caching available in ASP.NET and which caching technique is right for which scenario. We will also try to see how can we customize the caching behavior so that it suits our needs.


As ASP.NET web developers, we are mostly involved in developing web pages that are dynamic, i.e., contents coming from databases, Server directories, XML files or getting pulled from some other websites. Caching means to store something in memory that is being used frequently to provide better performance. Now can we think of the usability of caching in ASP.NET.

Let us imagine a scenario when the contents of a web page are being pulled from a database. The user asks for contents depending on some criteria. Now if the database is getting changed very frequently that even between two requests of same user, we anticipate database change, then we can in no way cache the data that the user is requesting. But if the database is not getting changed that frequently, we can have some caching in place so that if the user is requesting the same data very frequently, we don't hit the database everytime (since we know contents are not changed).

The two keys terms here are frequency and criteria. Frequency is the number of times we are anticipating the user requests for a particular page and criteria is what governs the uniqueness of result that is being displayed on the page.

Frequency is important because we need to figure out the interval in which database is changing and compare it with the frequency of user requests so that we can have caching in place and also make sure that user is not viewing outdated data.

Criteria is important because we need to make sure that we have caching implemented for the page on every unique criteria. It should not be the case that user is requesting contents based on criteria01 and we are showing him the cached results of criteria00 (cached earlier for him).

So with all this theory in mind, let's go ahead and see how ASP.NET provides caching features without us writing a lot of code to manage the same.

Types of Caching

There are two types of caching available in ASP.NET:

  1. Page Output Caching
  2. Application Caching

Page Output Caching

Page output caching refer to the ability of the web server to cache a certain webpage after user request in its memory so that further requests for the same page will check for the cached page's validity and will not result in resource usage (DB access or file access) and the page will be returned to user from cache.

Now the question is how can we ensure that the user is not viewing the outdated data. ASP.NET provides us various configuration options which will let us program in such a way that we can ensure that the user never gets stale data.

Let us have a simple web page with a textbox, button and a label. Right now, the caching is not enabled for this page so everytime the postback occurs, the request to the web server is made. We can verify this by displaying the current time in the label.

protected void Page_Load(object sender, EventArgs e)
    Label1.Text = DateTime.Now.ToLongTimeString();

Now let us go ahead and enable caching for this page by adding the following declaration to the page:

<%@ OutputCache Duration="30" VaryByParam="none" %>

Here we are saying that this page should be cached for 30 seconds, We can verify this by pressing the button. The time string will not change for 30 seconds and the second property VaryByParam specifies that caching doesn't depend on anything doing so can lead to a situation where user can see stale data, like in our case for 30 seconds if we write something in textbox and do a postback, it will keep reverting to the old data that was in the textbox at the time page was cached.

caching images

So it's a good idea to say that the cached page is not valid if the data in textbox is changed so let's do that now:

<%@ OutputCache Duration="30" VaryByParam="TextBox1" %>

So now we can see that the page output will be cached as long as the contents of the textbox are not changed. If we change the contents of the textbox, then the server processes the page again and then caches it again.

caching images

So what we saw is that we can specify the Duration the page should be cached which is related to the talk about frequency we did earlier. The Duration should be chosen so that during that time we are not expecting any change in data and for the criteria, we saw how we can use VaryByCustom to make sure that the output for every different criteria is generated and the cached copy is not just presented to the user.

Let us look as some other parameters that we can use to customize caching behavior.

  • VaryByParam: List of strings that are sent to server via POST that are checked to validate cache
  • VaryByControl: List of controls whose value will determine the validity of cache
  • SqlDependency: Defines the Database-tablename pair on which the validity of cache depends
  • VaryByCustom: Used for custom output cache requirements
  • VaryByHeader: HTTPs header that determines the cache validity

If we need different output pages based on query string, then we can specify the list of querystring parameters here or we can simply say VaryByParam ="*" to do the same for all querystring parameters. Now let us just have a quick look at what we need to do if we need to change the cached page based on query string parameter.

<%@ OutputCache Duration="30" VaryByParam="name" %>
protected void Button2_Click(object sender, EventArgs e)
    int name;
    if (Request.QueryString["name"] == null)
        name = 1;
        name =  Convert.ToInt32(Request.QueryString["name"]) + 1;
    Response.Redirect("varybyqs.aspx?name=" + name.ToString());

caching images

Partial Page Caching

Also, if we have a requirement for partial page caching (Fragment caching), we can simply use the controls that require caching and put them in a user control. We can then use the same above mentioned technique to enable caching behavior in the custom control and we have partial page caching in place. (See the code for implementation.)

caching images

Note: The above mentioned approaches enabled us to use caching by using declarations on the page. We can also control caching programmatically.

Application Caching

Application data caching is a mechanism for storing the Data objects on cache. It has nothing to do with the page caching. ASP.NET allows us to store the object in a Key-Value based cache. We can use this to store the data that need to cached. Let us work on the same example and try to store the DateTime object in the Application Cache now.

protected void Page_Load(object sender, EventArgs e)
    if (IsPostBack == false)
        Cache["time"] = DateTime.Now;

    Label1.Text = ((DateTime)Cache["time"]).ToLongTimeString();

What this code will do is that it will store the DateTime object in application cache and will keep displaying the time of initial request by using the object from the cache.

caching images

There are various parameters associated with application data caching that can be used to control its behavior.

  • Dependencies: Any file or item in cache that invalidates this cache item
  • absoluteExpiration: Absolute time when this object should be removed from cache
  • slidingExpiration: Relative time when this object should be removed from the cache
  • priority: Defines the priority of the item. This is useful when server runs out of memory as in that case it start removing items from cache with lowest priority first
  • onRemoveCallBack: This is the event handler that will be called when the object is removed from cache. It gives us a place to take further actions.

Note: The source code contains individual page for each technique. Run each page separately to see caching in action.

Points of Interest

Let us now try to summarize what we have seen so far:

  • The ASP.NET provides caching features so that the developers can use them instead of writing all the caching logic manually.
  • Page output caching should be used when we want to cache complete web pages based on some criteria and for some specific time.
  • Application caching should be used when we want to cache custom objects to use later.
  • Application caching provides a lot of parameters to customize its behavior to have more fine grained control.


  • 21 Feb 2012: Beginner's tutorial on ASP.NET caching


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more:[^]

  • Microsoft MVP 2015

Comments and Discussions

Questionunable to comment on your blog Pin
Karthik Chintala16-Feb-16 4:47
Karthik Chintala16-Feb-16 4:47 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun17-Dec-14 20:33
Humayun Kabir Mamun17-Dec-14 20:33 
Questionquestion Pin
Karmesh_Madhavi10-Dec-14 1:02
Karmesh_Madhavi10-Dec-14 1:02 
GeneralMy vote of 5 Pin
Sibeesh Venu1-Aug-14 16:19
professionalSibeesh Venu1-Aug-14 16:19 
GeneralMy vote of 5 Pin
Antariksh Verma8-Aug-13 20:11
professionalAntariksh Verma8-Aug-13 20:11 
QuestionWhere Caching is Store? Pin
deep0627-Nov-12 0:12
deep0627-Nov-12 0:12 
AnswerRe: Where Caching is Store? Pin
Rahul Rajat Singh27-Nov-12 0:33
professionalRahul Rajat Singh27-Nov-12 0:33 
AnswerArticle of the Day on Microsoft's site Pin
Rahul Rajat Singh2-Nov-12 17:58
professionalRahul Rajat Singh2-Nov-12 17:58 
QuestionMy Vote of 4 Pin
Alireza_136211-Oct-12 22:20
Alireza_136211-Oct-12 22:20 
GeneralMy vote of 4 Pin
Manoj Kumar Choubey19-Mar-12 19:52
professionalManoj Kumar Choubey19-Mar-12 19:52 
GeneralMy vote of 3 Pin
SoulStone-BR6-Mar-12 15:18
professionalSoulStone-BR6-Mar-12 15:18 
GeneralMy vote of 3 Pin
musale pradeep rao29-Feb-12 19:26
musale pradeep rao29-Feb-12 19:26 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey29-Feb-12 18:07
professionalManoj Kumar Choubey29-Feb-12 18:07 
GeneralMy vote of 3 Pin
Dean Oliver22-Feb-12 8:38
Dean Oliver22-Feb-12 8:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.