16.14 Using Page Output Caching

 <  Day Day Up  >  

You want to cache the final output of an ASP .NET page to improve performance.


Technique

Page output caching in ASP.NET allows you to cache the response content from a page to speed retrieval of content that is updated periodically. To enable page output caching, place a @OutputCache directive at the top of the .aspx file. This directive has three possible attributes of which only two are required. The two required attributes include Duration and VaryByParam . The Duration attribute denotes the time in seconds before the cached response is invalid and a new response stream should be generated. The VaryByParam attribute caches different copies of the result. For instance, an ASP.NET page can produce output denoting weather patterns for a certain country but produce different results for different countries . The VaryByParam attribute allows you to control how ASP.NET should determine the correct result to extract from the cache. The attribute that is not required is Location . The caching that occurs is based on HTML 1.1 standards and is not an ASP.NET-only concept. Caching can occur on the server hosting the application, on a proxy server, or on the client's machine itself, and you send it within the header value Cache-Control . The possible values for the Location attribute include Any , Client , Downstream , Server , or None . An example of a page with caching enabled would appear like the following:

 
 <%@ OutputCache Duration="100" VaryByParam="none" Location="Server"%> 

Comments

Page output caching can provide noticeable performance improvements to high traffic Web sites. For instance, let's assume a page is accessed 100 times by multiple users in 1 minute. With no caching enabled on the ASP.NET page, the database will be accessed 100 times, resulting in a large data transfer. With caching enabled, the database is accessed only once and the processing of the ASP.NET page happens only once, with the resultant cached output sent to each client.

Instead of using the OutputCache directive, you can also do so programmatically. You access the Cache property through the Response object. To set the cache duration, call the SetExpires method, passing the number of seconds for the duration. To set the cache location, call the SetCacheability method, passing a value from the HttpCacheability enumerated data type. For example, to cache a document on both the client and proxy server for a duration of 60 seconds, the code would appear as follows :

 
 Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetValidUntilExpires(true); 
 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net