Introduction

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.

Background

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.

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

<%@OutputCacheDuration="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:

<%@OutputCacheDuration="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 string parameter.

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

Share

About the Author

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.

It is stored in Server Memory. Let me quote a very good answer from StackOverflow here:

"The default behaviour is to store the content in memory in the same way as HttpRuntime.Cache (actually in an internal HttpRuntime.CacheInternal which behaves similarly to the publicly visible cache), but in ASP.NET 4.0 you can write your own provider to store the content however you wish."

Twenty years from now you will be more disappointed by the things that you didn't do than by the ones you did do. So throw off the bowlines. Sail away from the safe harbor. Catch the trade winds in your sails. Explore, Dream. Discover.