OutputCache commands in ASP. NET

Source: Internet
Author: User

Use the @ OutputCache command

Use the @ OutputCache command to implement general requirements for page output cache. @ OutputCache command the header Declaration of the user control contained in the asp.net page or page. This method is very convenient. You only need a few simple attribute settings to implement the page output Cache Policy. @ OutputCache command declaration code.

@ OutputCache command code

 
 
  1. <%@ 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, the @ OutputCache command contains 10 attributes, including CacheProfile, NoStore, Duration, Shared, Location, SqlDependency, VaryByControl, VaryByCustom, VaryByHeader, and VaryByParam. These attributes are used to set the cache time, cache item location, and SQL data cache dependency. The following describes the basic concepts of the above attributes.

CacheProfile

Defines the name of the cache settings associated with this page. Is an optional attribute. The default value is null (""). Note that the @ OutputCache command in the user control does not support this attribute. When this attribute is specified on the page, the attribute value must match the name of an available item in the outputCacheProfiles element in the <outputcachesetfiles> Configuration section of the Web. config file. If the name does not match the configuration file, an exception is thrown.

NoStore

This attribute defines a Boolean value to determine whether to block secondary storage of sensitive information. Note that the @ OutputCache command in the user control does not support this attribute. Setting this attribute to true is equivalent to executing the code "Response. Cache. SetNoStore ();" during the request ();".

Duration

Used to set the cache time for pages or user controls. The Unit is seconds. By setting this attribute, you can create an expiration Policy for the HTTP response from the object and automatically cache the page or user control output. Note that the Duration attribute is required. Otherwise, the analyzer error may occur.

Shared

This attribute defines a Boolean value to determine whether the output of a user control can be shared by multiple pages. The default value is false. Note that the @ OutputCache Command included in the asp.net page does not support this attribute.

Location

Specifies the location of the output cache. Its Attribute values are OutputCacheLocation enumeration values, which are Any, Client, Downstream, None, Server, and ServerAndClient. The default value is Any, indicating that the output cache can be used for all requests, including the client browser, proxy server, or server that processes the request. Note that the @ OutputCache command in the user control does not support this attribute.

SqlDependency

This attribute identifies the string value of a group of database/table name pairs. The output cache of pages or controls depends on these name pairs. Note: The SqlCacheDependency class monitors the tables in the database on which the output cache depends. Therefore, when items in the table are updated, table-based round robin is used to remove these items from the cache. When the notification is used with the CommandNotification value in SQL Server 2005), The SqlDependency class is used to register the query notification with the SQL Server 2005 Server. In addition, the CommandNotification value of the SqlDependency attribute is only valid on the asp.net page. The control can only use table-based round robin For the @ OutputCache command.

VaryByControl

This attribute uses a semicolon-separated string list 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 attribute is required in the @ OutputCache command unless the VaryByParam attribute is already included.

VaryByCustom

It is used to customize any text required by the output cache. If the property value is browser, the cache varies with the browser name and major version information. If you enter a custom string, you must re-write HttpApplication. GetVaryByCustomString in the Global. asax file of the application.

VaryByHeader

This attribute contains the HTTP header list separated by semicolons to change the output cache. When this attribute is set to multiple headers, the output cache contains different versions of a request document for each specified header. The VaryByHeader attribute enables cache items in all HTTP 1.1 caches, not limited to asp.net caches. The @ OutputCache command in the user control does not support this attribute.

VaryByParam

This attribute defines a semicolon-separated string list to change the output cache. By default, these strings correspond to the query string values sent using the GET method attribute, or to parameters sent using the POST method. When this attribute is set to multiple parameters, the output cache contains different versions of the Request Document for each specified parameter. Possible values include "none", "*", and any valid query string or POST parameter names. It is worth noting that this attribute is required when the asp.net page is cached. It is also required for user controls, unless the VaryByControl attribute is included in the @ OutputCache command of the user control. If not, a analyzer error occurs. If you do not need to change the cache content with any specified parameter, you can set this value to "none ". If you want the output cache to change according to all parameter values, set the attribute to "*".

The following lists two sample codes using the @ OutputCache command.

Sample Code 1 using @ OutputCache

 
 
  1. <%@ OutputCache Duration="100" VaryByParam="none"%>  

The preceding example shows the basic application of the @ OutputCache command. It indicates that the validity period of the page output cache is 100 seconds, and the page does not change with any GET or POST parameters. The request received when the page is still cached is provided by the cached data. After 100 seconds, the page data will be removed from the cache, And the next request will be processed explicitly and the page will be cached again.

Sample Code 2 using @ OutputCache

 
 
  1. <%@ OutputCache Duration="100" VaryByParam="location;firstname" %>  

The above @ OutputCache command sets the page output cache to be valid for 100 seconds, and sets the output cache based on the query string parameter location or firstname. For example, assume that the client request is "http: // localhost/default. aspx? Location = beijing ", the page will be processed as a cache.

Use the page output cache API

The preceding section describes how to use the @ OutputCache command to set the output cache. This method is easy to use and favored by developers. In addition, asp.net 2.0 also extended a method to use the output cache API to program the page output cache from asp.net 1.x relay. The core of this method is to call System. Web. HttpCachePolicy. This class mainly includes methods used to set cache-specific HTTP headers and to control the asp.net page output cache. Compared with the HttpCachePolicy class in. NET Framework 1. x, the HttpCachePolicy class in. NET Framework 2.0 has been expanded and developed. It mainly adds some important methods, such as the SetOmitVarStar method. As there are many HttpCachePolicy class methods, the following describes some common methods.

SetExpires Method

Used to set the absolute cache expiration time. Its parameter is an instance of the DataTime class, indicating the absolute expiration time.

SetLastModified Method

Used to set the Last-Modified HTTP header of the page. The Last-Modified HTTP header indicates the Last modification time of the page, and the cache will rely on it for timing. This method fails if the cache restriction hierarchy is violated. The parameter of this method is an instance of the DataTime class.

SetSlidingExpiration Method

This method sets the cache expiration time from the absolute time to the adjustable time. The parameter is a Boolean value. When the parameter is true, the Cache-Control HTTP header is updated with each response. This expiration mode is the same as the IIS configuration option that adds the expiration header to all output sets relative to the current time. When the parameter is set to false, this setting is retained, and any attempt to enable and adjust the expiration time will still fail. This method is not directly mapped to the HTTP header. It is used by subsequent modules or auxiliary requests to set the Cache Policy of the source server.

SetOmitVaryStar Method

The method added by asp.net 2.0. It is used to specify whether the response should contain the vary: * Header when partitioning by parameters. The method parameter is a Boolean value. To indicate that HttpCachePolicy does not use the * value for its VaryByHeaders attribute, the value is true; otherwise, the value is false.

SetCacheability Method

Set the Cache-Control HTTP header of the page. This header is used to control the way documents are cached on the network. This method has two overload methods, with different parameters. The parameters of one overload method are the HttpCacheability enumeration values, including NoCache, Private, Public, Server, ServerAndNoCache, and ServerAndPrivate definitions of these enumeration values. For details, refer to MSDN ). The other method has two parameters: one is the HttpCacheability enumeration value and the other is a string, indicating the Cache Control extension added to the header. Note that the field extension is valid only when used together with the Private or NoCache command. If the combination of incompatible commands and extensions, this method will cause invalid parameter exceptions.

The following example describes how to use the HttpCachePolicy class of the page cache API.

HttpCachePolicy class sample source code

Response. Cache. SetExpires (DateTime. Now. AddSeconds (60 ));

Response. Cache. SetExpires (DateTime. Parse ("6:00:00 "));

The Cache attribute of the Response class is used to obtain the page Cache Policy. The data type of this attribute is HttpCachePolicy. You can call Response. Cache to obtain the HttpCachePolicy instance, and then set the output Cache of the current page. As shown in the above Code, 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 =" 60 "VaryByParam =" none "%> ". The second line of code sets the absolute cache expiration time to six o'clock P.M. on the current day.

Page output cache application

The preceding two sections describe how to use the @ OutputCache command and API to set the page output cache function. In fact, the two methods have their own advantages. The @ OutputCache command method is relatively simple, but the flexibility is poor. By using APIs, You can dynamically modify cache configurations during runtime to handle more complex requirements. This section uses this knowledge to implement a simple example of the page output cache application, which involves both the @ OutputCache command application and the page output cache API. The example result 1 and figure 2 are shown.

Figure 1 stopping Cache

 

Figure 2 Cache execution

1. The application initially displays the time when the cache is stopped. When you refresh the page, the URL is http: // localhost: 5159/Code % 2012-1/Default. aspx, where 5159 is the temporary server port number), the time value changes at any time to display the latest time. 2. Click the cache time Hyperlink and redirect the page to http: // localhost: 5159/Code % 2012-1/Default. aspx? Location = beijing. The time displayed on the page is cached and the data expiration time is 5 seconds. If you constantly refresh the page, the value changes once every five seconds.

This example has two key points. One is to stop the cache at runtime, and the other is to configure the @ OutputCache command. These two points have been implemented in the application Default. aspx file. The source code of the file is listed below.

Source code of the Default. aspx File

 
 
  1. <% @ Page Language ="C #"AutoEventWireup ="True"CodeFile ="Default. aspx. cs"Inherits ="_ Default"%>
  2.  
  3. <% @ OutputCache Duration ="5"VaryByParam ="Location"%>
  4.  
  5. <! DOCTYPE html PUBLIC"-// W3C // dtd xhtml 1.1 // EN" Http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
  6.  
  7. <Html xmlns =Http://www.w3.org/1999/xhtml">
  8.  
  9. <Script language ="C #"Runat ="Server">
  10.  
  11. VoidPage_Load (ObjectSender, EventArgs e)
  12.  
  13. {
  14.  
  15. // Set to store only the cached data on the server 
  16.  
  17. Response. Cache. SetCacheability (HttpCacheability. Server );
  18.  
  19. StringTemp_location = Request. QueryString ["Location"];
  20.  
  21. // If the location is empty, the cache is not cached. Otherwise, the cache is declared and executed according to the @ OutputCache instruction. 
  22.  
  23. If(Temp_location =Null)
  24.  
  25. {
  26.  
  27. // Stop all Server caches in the current response 
  28.  
  29. Response. Cache. SetNoServerCaching ();
  30.  
  31. Label1.Text ="Cache stop time :"+ DateTime. Now. ToString ();
  32.  
  33. }
  34.  
  35. Else 
  36.  
  37. {
  38.  
  39. Label1.Text ="Set the cache time :"+ DateTime. Now. ToString ();
  40.  
  41. }
  42.  
  43. }
  44.  
  45. </Script>
  46.  
  47. <Head id ="Head1"Runat ="Server">
  48.  
  49. <Title> example 12-1 </title>
  50.  
  51. <Link id ="InstanceStyle"Href ="StyleSheet.css"Type ="Text/css"Rel ="Stylesheet"/>
  52.  
  53. </Head>
  54.  
  55. <Body>
  56.  
  57. <Form id ="Form1"Runat ="Server">
  58.  
  59. <Div>
  60.  
  61. <Fieldset style ="Width: 240px">
  62.  
  63. <LegendClass="MainTitle"> Set the page output cache </legend>
  64.  
  65. <Br/>
  66.  
  67. <Center> <asp: Label ID ="Label1"Runat ="Server"CssClass ="CommonText"> </Asp: Label> </center>
  68.  
  69. <Br/>
  70.  
  71. <A href ="Default. aspx? Location = beijing" Class="LittleMainTitle"> Cache time </a> <br/>
  72.  
  73. </Fieldset>
  74.  
  75. </Div>
  76.  
  77. </Form>
  78.  
  79. </Body>
  80.  
  81. </Html>

As shown in the bold code above, the @ OutputCache command in the Code header sets the Duration and VaryByParam attributes, which indicate that the data expiration time is 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, the SetCacheability method must be used to set the data cache to be stored on the server. Then, the location parameter value of QueryString is obtained, and finally, it is determined based on the location parameter value. If the location parameter value is null, call the SetNoServerCaching method to stop the cache of all servers in the current response and display the current time value. Although the @ OutputCache command configures the page output cache, the page output cache function is not executed. If the location parameter value is not empty, the current time value is displayed. In this case, the configuration content of the @ OutputCache command is executed.

 
 
  1. < %@ OutputCache NoStore="True" Duration="15" Location="Any" VaryByControl="OC" VaryByCustom="browser" VaryByHeader="headers" VaryByParam="none" %> 
  1. Differences between Bind and Eval in ASP. NET: two types of binding
  2. Simple common ASP. NET Code 2)
  3. Simple common ASP. NET code 1)
  4. ASP. NET tips: Use of unmanaged COM components
  5. Another implementation of concatenating strings in ASP. NET: Response. Write

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.