Asp.net| Cache | page Static page All content is saved in server memory. When there is another request, the system outputs the relevant data in the cache directly until the cached data expires. In this process, the cache does not need to go through the page processing lifecycle again. This reduces request response time and improves application performance. Obviously, the page output cache is suitable for pages that do not need to update data frequently, and that consume a lot of time and resources to compile a build. For pages where the data is often updated, it does not apply. By default, ASP.net 2.0 enables page output caching, but does not cache the output of any response. The developer must pass the settings so that some of the page's responses become part of the cache.
There are two ways to set up page output caching: One is to use the @ OutputCache directive and the other is to use the page output caching API. The @ OutputCache directive was once seen in ASP.net 1.x and has been inherited and enhanced in ASP.net 2.0. The page output caching API mainly refers to the HttpCachePolicy class.
using the @ OutputCache directive
With the @ OutputCache directive, you can implement a general need for page output caching. The @ OutputCache directive declares the head of a user control contained in a ASP.net page or page. This approach is very convenient, with just a few simple property settings, you can implement the page's output caching strategy. The @ OutputCache directive declares the following code.
@ OutputCache Instruction Code
|
<%@ OutputCache CacheProfile= " nostore=" True | False " Duration=" #ofseconds " Shared=" True | False " Location=" any | Client | downstream | Server | None | ServerAndClient " sqldependency=" Database/table Name pair | CommandNotification " VaryByControl=" ControlName " varybycustom=" Browser | CustomString " varybyheader=" Headers " varybyparam=" ParameterName "%>
|
As shown above, there are 10 properties in the @ OutputCache directive, which are CacheProfile, Nostore, Duration, Shared, Location, SqlDependency, VaryByControl, VaryByCustom, VaryByHeader and VaryByParam. These attributes set the cache time, the location of the cache entry, the SQL data cache dependency, and so on. The basic concepts of the above properties are briefly described below.
CacheProfile
The name used to define the cache settings associated with the page. is an optional property and the default value is a null character (""). Note that the @ OutputCache directive contained in the user control does not support this property. When this property is specified in the page, the property value must match the name of one of the available items in the outputCacheProfiles element in the Web.config file <outputCacheSettings> configuration section. If this name does not match the configuration file entry, an exception is thrown.
Nostore
This property defines a Boolean value that determines whether to block level two storage of sensitive information. Note that the @ OutputCache directive contained in the user control does not support this property. Setting this property to true is equivalent to executing code "Response.Cache.SetNoStore ()" during the request.
Duration
Time to set the page or user control cache. The unit is seconds. By setting this property, you can establish an expiration policy for HTTP responses from objects and automatically cache page or user control output. It should be noted that the Duration property is required, or it will cause a parser error.
Shared
This property defines a Boolean value that determines whether the output of a user control can be shared by multiple pages. The default value is False. Note that the @ OutputCache directive contained in the ASP.net page does not support this property.
Location
Used to specify the location of the output cache entry. Their property values are outputcachelocation enumerated values, which are any, Client, downstream, None, server, and ServerAndClient. The default value is any, which means that the output cache is available for all requests, including the client browser, the proxy server, or the server that handles the request. Note that the @ OutputCache directive contained in the user control does not support this property.
SqlDependency
This property identifies the string value of a set of database/table name pairs, and the output caching of the page or control depends on these name pairs. Note: The SqlCacheDependency class monitors the tables in the database that the output cache relies on, so when items in the table are updated, the table based polling is used to remove the items from the cache. When notified (in SQL Server 2005) is used with the CommandNotification value, the SqlDependency class is eventually used to register query notifications with the SQL Server 2005 server. In addition, the CommandNotification value of the SqlDependency property is valid only in the ASP.net page. Control can only use a table based poll for the @ OutputCache directive.
VaryByControl
This property uses a semicolon-delimited list of strings to change the output cache of the user control. These strings represent the id attribute values of the ASP.net server control declared in the user control. This property is required in the @ OutputCache directive unless the VaryByParam property is already included.
VaryByCustom
Any text that is used to customize the output caching requirements. If you give the property value a browser, the cache will vary depending on the browser name and the major version information. If you enter a custom string, you must override the HttpApplication.GetVaryByCustomString method in the application's Global.asax file.
VaryByHeader
This property contains a semicolon-delimited list of HTTP headers that are used to change the output cache. When this property is set to multiple headers, the output cache contains a different version of the requested document for each specified header. The VaryByHeader property enables cache entries in all HTTP 1.1 caches, not limited to the asp.net cache. This property is not supported by the @ OutputCache directive in the user control.
VaryByParam
This property defines a semicolon-delimited list of strings that are used to change the output cache. By default, these strings correspond to the query string values sent with the Get method property, or to parameters that are sent with the Post method. When this property is set to multiple parameters, the output cache contains a different version of the requested document for each specified parameter. Possible values include "none", "*", and any valid query string or post parameter name. It is important to note that this property is required when the output caches asp.net pages. It is also required for user controls, unless the VaryByControl attribute is already included in the @ OutputCache directive of the user control. If it is not included, a parser error occurs. If you do not want the cached content to change with any of the specified parameters, you can set the value to none. If you want the output cache to change based on all parameter values, set the property to "*".
The following is a list of two sample codes that use the @outputcache directive.
Using the @ OutputCache sample code 1
|
<%@ OutputCache duration= varybyparam= "None"%>
|
The above example is the basic application of the @ OutputCache directive, which indicates that the page output cache is valid for 100 seconds and that the page does not change with any get or post parameters. Requests that are received while the page is still cached are serviced by the cached data. After 100 seconds, the page data is removed from the cache and then the next request is explicitly processed and the page is cached again.
Using the @ OutputCache sample code 2
|
<%@ OutputCache duration= varybyparam= "Location;firstname"%>
|
The above @ OutputCache directive sets the expiration date of the page output cache to 100 seconds and sets the output cache according to the query string parameter location or FirstName. For example, assuming that the client request is "http://localhost/default.aspx?location=beijing", the page will be treated as a cache.
using the page output caching API
The settings for output caching are implemented using the @ OutputCache directive. This method is easy to do, won the favor of developers. In addition, ASP.net 2.0 inherits and extends a way to programmatically set page output caching using the output caching API from ASP.net 1.x. The core of the method is to invoke System.Web.HttpCachePolicy. This class consists primarily of methods for setting cache-specific HTTP headers and methods for controlling asp.net page output caching. Compared to the HttpCachePolicy classes in the. NET Framework 1.x, the HttpCachePolicy classes in the. NET Framework 2.0 have been expanded and developed. The main method is to add some important methods, such as Setomitvarstar method and so on. Due to the large number of HttpCachePolicy class methods, the following briefly describes some common methods.
SetExpires method
The absolute time to set the cache expiration. Its argument is an instance of a Datatime class that represents the absolute time of expiration.
Setlastmodified method
The last-modified HTTP header that is used to set the page. The Last-modified HTTP header represents the time the page was last modified, and the cache relies on it for timing. This method fails if the cache restriction hierarchy is violated. The parameter of the method is an instance of a Datatime class.
Setslidingexpiration method
This method sets the cache expiration from an absolute time to an adjustable time. The parameter is a Boolean value. When the argument is true, the Cache-control HTTP header is updated with each response. This expiration mode is the same as the IIS configuration options that add an expiration header to all output sets relative to the current time. When the argument is false, the setting is preserved, and any attempt to enable adjustable expiration will fail statically. This method does not map directly to the HTTP header. It sets the source server caching policy for subsequent modules or secondary requests.
Setomitvarystar method
ASP.net 2.0 new method. Used to specify whether the response should contain a vary:* header when differentiating by parameter. The method parameter is a Boolean value to indicate that HttpCachePolicy does not use the * value for its VaryByHeaders property, or false.
SetCacheability method
The Cache-control HTTP header that is used to set the page. This header is used to control how documents are cached on the network. There are two ways to overload the method, and the difference is the parameters. The argument for an overloaded method is a HttpCacheability enumeration value, including NoCache, Private, Public, Server, ServerAndNoCache, and serverandprivate (for definitions of these enumerated values, Refer to MSDN). The other method has two parameters, one parameter is the HttpCacheability enumeration value, and the other is a string representing the cache control extension added to the header. It should be noted that the field extension is valid only when used with private or nocache directives. If you combine incompatible directives and extensions, this method throws an invalid parameter exception.
The following example illustrates the use of the HttpCachePolicy class for the page cache API.
HttpCachePolicy class Sample source code
|
Response.Cache.SetExpires (DateTime.Now.AddSeconds (60));
Response.Cache.SetExpires (DateTime.Parse ("6:00:00pm"));
|
The cache property of the response class is used to get the page caching policy. The data type of this property is HttpCachePolicy. You can obtain a HttpCachePolicy instance by calling Response.Cache to achieve the settings for the current page output cache. As shown in the code above, the first line of code indicates that the output cache time is 60 seconds and the page does not change with any get or post parameters, equivalent to "<%@ OutputCache duration=" varybyparam= "None"%>. The second line of code sets the absolute time that the cache expires is 6 o'clock in the afternoon the same day.
page Output Caching application
The above subsections describe the content of using the @ OutputCache directives and APIs to set the page output caching feature. In fact, both methods have their advantages, and using the @ OutputCache directive method is simpler, but less flexible. Using the API approach, you can dynamically modify the cache configuration at run time to handle more complex requirements. This section utilizes this knowledge to implement a simple example of a page output caching application involving both the @ OutputCache directive application and the page output caching API. The example effects are shown in Figure 12-1 and figure 12-2.
Figure 1 How to stop caching effects figure 12-2 performing a cached effect chart
As shown in Figure 1, the application initially displays the time when the cache was stopped. When the user refreshes the page (the URL address is http://localhost:5159/Code%2012-1/Default.aspx, where 5159 is the server's temporary port number), the time value changes to show the current time. As shown in Figure 12-2, when the cache time hyperlink is clicked, the page is redirected to Http://localhost:5159/Code%2012-1/Default.aspx?location=beijing. At this point, the page display time is cached, data expiration time is 5 seconds. If you refresh the page constantly, the time value changes every 5 seconds.
The example in this section has two key points. The first is to implement the stop cache at runtime, and the second is to configure the @ OutputCache directive. These two points have been implemented in the application Default.aspx file, and the file source code is listed below.
Default.aspx File Source code
|
<%@ Page language= "C #" autoeventwireup= "true" codefile= "Default.aspx.cs" inherits= "_default"%>
<%@ OutputCache duration= "5" varybyparam= "Location"%>
! DOCTYPE HTML PUBLIC "-//w3c//dtd XHTML 1.1//en" "Http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"
void Page_Load (object sender, EventArgs e)
{
//Settings store cached data only on the server
Response.Cache.SetCacheability (httpcacheability.server);
string temp_location = request.querystring["Location"];
//Iflocationis empty,is not cached,Otherwise according to@ OutputCacheInstruction declaration Execution cache
if (temp_location = null)
{
//Stop all server caches for the current response
Response.Cache.SetNoServerCaching ();
Label1.Text = "Time to stop caching:"+ DateTime.Now.ToString ();
}
Else
{
Label1.Text = "Set the time of the cache:"+ DateTime.Now.ToString ();
}
}
<title> Sample 12-1 </title>
<link id= "Instancestyle" href= "Stylesheet.css" type= "Text/css" rel= "StyleSheet"/>
<body>
<form id= "Form1" runat= "Server"
<div>
<fieldset style= "width:240px"
<legend class= "Maintitle" to set page output caching </legend>
<BR/>
<center> <asp:label id= "Label1" runat= "Server" cssclass= "Commontext" > </asp:Label> </center>
<BR/>
< b>Cache time<BR/>
</fieldset>
</div>
</form>
</body>
|
As shown in the bold code, the @ OutputCache directive for the code header sets the duration and VaryByParam properties indicating that the data expires in 5 seconds. At the same time, the cache changes according to the parameter location. In addition, the code implements the Page_Load event handler. In this program, first of all, the SetCacheability method is used to set the data cache to be stored on the server, and then the location parameter value of the QueryString is obtained and, finally, judged according to the location parameter value. If the location parameter value is NULL, the Setnoservercaching method is invoked to stop all server caches for the current response and to display the current time value. Although the @ OutputCache directive is configured with page output caching, the page output caching function is not performed. If the location parameter value is not NULL, the current time value is displayed directly. In this case, the configuration content of the @ OutputCache directive is executed.