Caching refers to storing information for later retrieval, rather than generating it from scratch every time it's requested. For instance, a Web page can be cached so that it's delivered more quickly when it's requested the second time.
ASP.NET implements three types of caching, which are discussed in the following sections. Output CachingOutput caching refers to caching the entire output of a page request. You can specify the cacheability of a page or user control by using the OutputCache directive. Table 16.2 lists the attributes of this directive. Table 16.2. Attributes of the OutputCache Directive
Follow these steps to implement output caching for a Web page using the OutputCache directive:
In the previous example, note that the OutputCache directive requires the VaryByParam attribute. If the page output doesn't depend on any input parameters, you can use None as the value of this attribute; otherwise , use the name of the parameter to cause caching to be done on a per-parameter value basis. The HttpCachePolicy class enables you to set output caching for a page programmatically. The Cache property of the HttpResponse object provides access to the HttpCachePolicy class. The HttpResponse object can be accessed through the Response property of the Page or HttpContext class, as shown in the following code segment: private void Page_Load(object sender, System.EventArgs e) { lblTime.Text = DateTime.Now.ToLongTimeString(); Response.Cache.SetExpires(DateTime.Now.AddSeconds(15)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetValidUntilExpires(true); } In this code, manipulating the HttpCachePolicy object has exactly the same effect as setting the OutputCache directive did in the previous example. This example uses three methods of the HttpCachePolicy object. The SetExpires() method specifies an expiration time for the cached version of the page; in this case, it's 15 seconds from the time the page is generated. The SetCacheability() method specifies where output can be cached through the HttpCachePolicy enumeration: NoCache for no caching at all, Private to allow caching only on the client (the default value), Public to allow caching on any proxy server as well as on the client, and Server to cache the document only on the Web server. Finally, the SetValidUntilExpires() method with its parameter set to true tells the server to ignore client-side attempts to refresh the cached content until it expires . Caching multiple versions of a page is useful any time you have a page whose output depends on an input parameter. You can base such multiple-version caching on any HTTP header or browser attribute, but most commonly, you'll use the VaryByParam attribute to cache multiple values depending on a query string or form POST parameter. For example, if you have a page that is accessed using a URL such as http:// ServerName /GetCountryInfo.aspx?ddlCountries=Brazil and the rendering of this page depends on the query string parameter, you can cache the different versions of that page by using the following OutputCache directive: <%@ OutputCache duration="20" VaryByParam="ddlCountries"%> Here, ddlCountries is the name of a query string parameter and the cache duration is set to 20 minutes. This type of caching involves fewer round trips to the database server. In addition, the Web server can deliver the data from the output cache without dynamically generating the page at every request. As a result, caching helps in creating scalable and high-performance Web applications. You can also cache the output of a page on the basis of the control's value. For example, consider the following OutputCache directive: <%@ OutputCache duration="20" VaryByControl="ddlCountries"%> This directive caches the output for a page for 20 minutes based on the different values of the ddlCountries control. Fragment CachingFragment caching refers to caching part of a page. You can encapsulate a portion of a page into a user control and cache that portion of the page, while still forcing the rest of the page to be dynamically generated for each request. Fragment caching is similar to output caching, in which the output of a user control is cached. The OutputCache directive also caches user controls. Refer to Table 16.2 for information on the attributes of the OutputCache directive. You should specify either the VaryByParam attribute or the VaryByControl attribute in the OutputCache directive of the user control. You should also specify the Duration attribute to indicate how long the user control should be cached. Any number of user controls can exist in a page, and each of these user controls maintains caching on its own. While caching user controls, you should consider the following points:
Data CachingASP.NET also enables you to cache application data. In a Web application, data can be retrieved through expensive and time-consuming operations. Most of this data can change infrequently but be required often. The caching of arbitrary data is known as data caching or application data caching . The Cache class of the System.Web.Caching namespace enables you to cache data. The following lists some important facts about the application cache:
The Cache object can be easily accessed using the Cache property of the Page object or the HttpContext object. You can insert or add items to the data cache using the Insert() or Add() method of the Cache object, respectively. The Insert() method has four overloads that provide a choice to insert items in the cache by specifying parameters such as expiration time, sliding expiration time, cache dependency, cache priority, and callback method. The Add() method adds an item to the data cache and returns a reference of the added item. The Remove() method is called to explicitly remove items from the data cache. You can also easily insert data items into a data cache using indexers by providing a key and value, like so: Cache["CustomersDataSet"] = dsCustomers; |