Caching in ASP.NET
There are 3 types of Caching Techniques in ASP.NET:
- Output Caching
- Fragment Caching
- Data Caching
1. Output Caching: It is used to cache HTML page. But it should be used with those pages only which show only master data which never changes in your application and you don't want to connect with database again and again to take refreshed or updated data, otherwise, if used with Dynamic page which everytime takes refreshed data from server, will cause problems.
Directive for caching: <%@ OutputCache Duration="20" VaryByParam="None" %>
Caching can also be done on Client Side but it is not recommended. Because every time when user refreshed the page, the page will come from server not from cache. This will only work when user goes back to that page which was cached or user just type the url for that page. Just include Location keyword in cache directive to use client side caching.
<%@ OutputCache Duration="20" VaryByParam="None" Location="Client" %>
VaryByParam: It deals with the querystrings in urls. If it is set to "none", means whatever the querystring is, the page will be cached irrespective of it and the caching will take place according to the url.
Example: www.mySite.com?a=b, www.mySite.com?a=c, in both cases same page will be cached and querystring attached with url will be ignored.
If VaryByParam is set to "*", two different copies will be cached depending on the value of parameter "a".
If VaryByParam is set to "a", again two different copies will be cached as value of "a" is getting changed in both the urls.
If there are more parameters in querystring, those can also be set as VaryByParam="a;b;c"
VaryByHeader: Caching can also be done on the basis of HTTP headers.
<%@ OutputCache Duration="20" VaryByHeader="None" %>
2. Fragment Caching:
Same as that of Output Caching but instead of full page, a small portion of page is cached. Whatever the portion is to be cached, we have to make user control for that, and in that user control, we will put the output cache directive.
In both types of caching, no code is required just put outputCache directive.
Note: Caching is usually done on web servers not on application servers.
3. Data Caching: Here data is cached instead of HTML page. Coding is required here instead of adding any directive. Cache object is used to cache the data. Cache object is thread safe. Cache object automatically removes the values which get expired. So, one must be careful while retrieving any value from cache object. One must check whether that value exist in cache object or not before retrieving the value, otherwise you may get Null Reference Exception.
Cache.Insert inserts value in the Cache object.
Cache("myValue") get myValue previously stored in Cache object.