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:
- Page Output Caching
- 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.
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.
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
<%@ OutputCache Duration="30" VaryByParam="name" %>
protected void Button2_Click(object sender, EventArgs e)
if (Request.QueryString["name"] == null)
name = 1;
name = Convert.ToInt32(Request.QueryString["name"]) + 1;
Response.Redirect("varybyqs.aspx?name=" + name.ToString());
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.)
Note: The above mentioned approaches enabled us to use caching by using declarations on the page. We can also control caching programmatically.
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
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.
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