Malaika Consultants LLC

ASP.NET Caching – A Primer : Part 1 – Output Caching

by Swanand Mokashi 19. August 2010 07:40

Introduction

ASP.NET Caching has to be the one the most under utilized feature of ASP.NET . Caching is a process of storing frequently used data on the server to fulfill subsequent requests. The browser kind of does something similar for you on the client side, where it caches the webpage ,images etc to display them much faster the next time. ASP.NET caching does the same thing for you on the server side. The frequently used data is stored in the server memory and as you can imagine memory access is a lot faster than recreating the webpage from scratch. This leads to boosting the performance, scalability and availability of the website.

There are 3 different ways you can use ASP.NET caching : output caching,  partial page (UserControl) caching and programmatic caching. In this part, we will look at the output caching.

Output caching

Output caching enables to cache the entire dynamic HTTP page in the server memory and enable to retrieve it from the memory instead of recreating it. This means if you are using a master page for your site, for this particular webpage both the master page content and the content page content will be cached.

To achieve output caching is very simple : you need to add an OutputCache page directive at the top of an aspx page:

<% OutputCache Duration=”120” VaryByParam=”None” %>

The above example directive will store the webpage in cache for 120 seconds. The VaryByParam attribute determines which versions of the page are cached. The other available attributes are : VaryByHeader, VaryByControl, VaryByCustom and Location. Let us take a look at each of them

VaryByParam

You can specify which Querystring parameters will cause a new version to be cached:

<% OutputCache Duration=”120” VaryByParam=”productId;manufacturerId;” %>

The above example means store a separate version of the page in cache for each combination of productId and manufacturerId. Bear in mind the number of cached versions for this page will be (number of distinct productId * number of distinct manufacturerId). You can also specify “*” as the value for the VaryByParam and a separate version will be cached for any differences in the Querystring parameters. 

VaryByHeader

You can specify VaryByHeader to save a version for each variation in one of more headers that the browser sends.

<% OutputCache Duration=”120” VaryByHeader=”User-Agent” %>

The above example will store a version for each variation of the user-agent (i.e. browsers) in the cache.

VaryByControl

You can specify the VaryByControl attribute to cache the rendered output of the a UserControl

Location

Defines if page output can be cached on a proxy or downstream client. Often omitted, so that caching is performed in the most efficient way. However, it is a good idea to include Location="Any" where you do not actually need to control the location

VaryByCustom

As with most features in ASP.NET if the standard features do not work for you, you can use your own custom logic which offers the most flexibility. For example, say you want to take the OutputCache to vary by a value in a cookie or a session variable or whatever you can use VaryByCustom. There is a special method GetVaryByCustomString that can be added to the Global.asax.

The GetVaryByCustomString gets called each time a page is requested and the function returns a value. A different version of the page is cached for each unique value is returned. A good example is suppose you want to cache a fairly static page but if this page (or its master page) stores the referrer of the page as a session variable (say you have an ad campaign leading to this page, and you are tracking where your visitor came from). If you cache the page as is, then the session variable will always be empty (or the value will be the same as the first time the page was requested and put in cache). Now if you pass this variable to another page (or to another site via your external links) this will pose a problem. You can change the GetVaryByCustomString method to return the value of the session variable and that will take care of the issue.

The GetVaryByCustomString method has an input parameter arg passed in which is the same as what you type as the value for “VaryByCustom”. So in the above example if you use :

<% OutputCache Duration=”120” VaryByHeader=”Referrer” %>

The GetVaryByCustomString can be used as below :

public override string GetVaryByCustomString(HttpContext context, string arg)
    {
        switch (arg.ToLower())
        {
            case "referrer":
                //Get your session value and return it
                return "your_session_value";
                break;
            case "other":
                //You can have other pages that use the VaryByCustom attribute
                break;
        }
    }

Extending <OutputCache>

With ASP.NET 4.0 it is interesting that now you can extend the <OutputCache> directive to work off your own custom ways to cache. This way if you want to store your cache on the disc, cloud or database or anywhere else, you can do it.

In order to achieve this, you will need to create a custom cache provider class (inherited from System.Web.Caching.OutputCacheProvider) and override the Add(), Get(), Remove() and Set() methods.

The <outputCache> sub section under the <caching> section in the web.config has a new subelement <providers> and you can add your own output cache provider in there. Of course as with everything in ASP.NET, you can override this default cache provider by adding  the providerName attribute to the OutputCache directive for an individual page itself.

Hope this was a good primer on ASP.NET output caching. In the next part, we will see how to do partial page caching

Technorati Tags: ,,

Tags: , , , ,

Coding

Comments

9/9/2010 1:59:08 AM #

Introduction  ASP. NET Caching has to be the one the most under utilized feature of ASP. NET .

Няня United States | Reply

9/10/2010 10:58:07 AM #

I appreciate the work that you have put into this page. Genuinely good,and informative. Thank You

Phil wasserman United States | Reply

9/10/2010 6:44:48 PM #

This is an amazing entry. Thanks for the excellent article you shared! I was finding for this entry for a long time, but I was not able to see a trusted website.

wow gold Belgium | Reply

9/10/2010 6:55:33 PM #

You've come to the Right Place if you're ready to pass your CDL Test on your PASS your Written Test today.

Billiards snooker Italy | Reply

9/10/2010 7:10:38 PM #

This is a very good posting, I discovered your web page searching aol for a similar subject and came to this. I couldnt get to much additional info on this article, so it was wonderful to find this one. I will probably be returning to look at some other articles that you have another time.

wow gold Macedonia (FYROM) | Reply

9/13/2010 2:32:47 PM #

Introduction  ASP. NET Caching has to be the one the most under utilized feature of ASP. NET .

Проститутки Москвы United States | Reply

9/14/2010 6:33:35 PM #

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

Проститутки СПБ United States | Reply

9/14/2010 10:58:32 PM #

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated. Great

Проститутки МСК United States | Reply

9/15/2010 5:56:21 PM #

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely helpful for me.

wow gold Argentina | Reply

9/15/2010 6:09:02 PM #

Hardwood Flooring are beautiful when done with experience. There is much that goes into wood floors that may go overlooked.  The difference between a expert and a rookie is like night and day.  Pay for the expert and you will have very long lasting remarkable floors

wow emblem Republic of the Philippines | Reply

9/16/2010 7:16:29 PM #

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated. Great post! Thanks for share.

Проститутки Москвы United States | Reply

9/21/2010 2:34:26 AM #

Thanks so much for posting this!  I have been pulling my hair out trying to resolve the issue... even rolling back to BE 1.6 which stopped the error but lost ability to use Recaptcha.  

Проститутки Киева United States | Reply

9/21/2010 8:34:29 PM #

Thanks so much for posting this!  I have been pulling my hair out trying to resolve the issue... even rolling back to BE 1.6 which stopped the error but lost ability to use Recaptcha.  

Киевские проститутки United States | Reply

9/22/2010 6:58:03 PM #

Лучший эротический массаж в Киеве от лучших девушек Киева, массажный салон Леди приглашает любителей всех видов массажа.

Массаж Киев United States | Reply

9/24/2010 8:53:21 PM #

Страхование в Украине реабилитируется. Многие страховые компании в конкурентной борьбе были вынуждены понизить ставки, но благодаря этому они смогли остаться на рынке страхования. Кроме того, страховики, чтобы оставаться на рынке вынуждены должным образом выплачивать страховые премии в результате наступления страхового случая. Поэтому именно сейчас очень выгодно покупать такие страховые продукты как страховка КАСКО или страхование ОСАГО.

страховка КАСКО United States | Reply

9/25/2010 12:03:31 PM #

Cool, there is actually some good points on here some of my readers will maybe find this relevant, will send a link, many thanks.

sony ericsson f305 price United States | Reply

9/27/2010 12:07:57 PM #

One of the more impressive blogs Ive seen.  Thanks so much for keeping the internet classy for a change.  Youve got style, class, bravado.  I mean it.  Please keep it up because without the internet is definitely lacking in intelligence.

dating service United Kingdom | Reply

9/28/2010 1:28:11 AM #

Лучшие смесители и сантехника в Киеве.

Смесители United States | Reply

10/4/2010 10:59:57 PM #

Great website...and cool article man...thanx for the great post...keep on posting such articles... Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

Смесители Grohe United States | Reply

2/18/2012 5:38:17 PM #

I agree with your thoughts here and I really love your blog! I've bookmarked it so that I can come back & read more in the future.

lojna me kerre United States | Reply

2/24/2012 2:30:55 PM #

You really need to get involved in a contest for one of the best web blogs on the web. I will recommend this portal!

John United States | Reply

2/26/2012 4:40:41 PM #

This is a very good tip particularly to those new to the blogosphere. Short but very precise information… Thank you for sharing this one. A must read post!

streaming movies United States | Reply

2/26/2012 4:55:02 PM #

I blog frequently and I truly appreciate your content. This article has really peaked my interest. I'm going to book mark your website and keep checking for new information about once a week. I opted in for your Feed as well.

salwar kameez United States | Reply

2/26/2012 5:16:49 PM #

Great info. Lucky me I discovered your website by accident (stumbleupon). I have book-marked it for later!

man with a van london United States | Reply

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



::: | © Malaika Consultants LLC | :::

Malaika Consultants LLC

Malaika Consultants LLC is a custom software development consulting firm located in Cary (Raleigh Durham Research Triangle AKA RTP area ) North Carolina. We offer our expert consulting services in the Microsoft .NET and related technologies. Our mission is to partner with you and ensure the success of your project. We have a team in the USA that will help you with your Information Technology needs and we strive to be truly "Your Information Technology Angels"

We are offering 1 hour of free consulting -- ASP.NET, SQL Server, IIS, anything. Contact us to get your free consulting

Recent Comments

Comment RSS