"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Thursday, January 24, 2013

Exploring more into caching in asp.net (Part 2)

 In order to cache a page's output, we need to specify an @OutputCache directive at the top of the page. The syntax is as shown below:



<%@ OutputCache Duration=5 VaryByParam="None" %>



As you can see, there are two attributes to this directive. They are:

Duration - The time in seconds of how long the output should be cached. After the specified duration has elapsed, the cached output will be removed and page content generated for the next request. That output will again be cached for 10 seconds and the process repeats.
VaryByParam - This attribute is compulsory and specifies the query-string parameters to vary the cache.
In the above snippet, we have specified the VaryByParam attribute as None which means the page content to be served is the same regardless of the parameters passed through the query-string.

If there are two requests to the same page with varying querystring parameters, e.g.: .../PageCachingByParam.aspx?id=12 and .../PageCachingByParam.aspx?id=15] and separate page content is generated for each of them, the directive should be:



<%@ OutputCache Duration=5 VaryByParam="id" %>
 
The page content for the two requests will each be cached for the time specified by the Duration attribute 
To specify multiple parameters, use semicolon to separate the parameter names. If we specify the VaryByParam attribute as *, the cached content is varied for all parameters passed through the querystring.

Some pages generate different content for different browsers. In such cases, there is provision to vary the cached output for different browsers. The @OutputCache directive has to be modified to:



<%@ OutputCache Duration=5 VaryByParam="id" VaryByCustom="browser" %>
 

This will vary the cached output not only for the browser but also its major version. I.e., IE5, IE 6, Netscape 4, Netscape 6 will all get different cached versions of the output.

If u had any trouble just ask, Happy to help u :)
Stay Tune...
Have a nice day... 'N happy Coding :)

No comments: