) ASP. NET page Cache

Source: Internet
Author: User


You can use either the @ OutputCache command or the page output cache API to set the page output cache. @ OutputCache commands have appeared in ASP. NET 1.x and are inherited and enhanced in ASP. NET 2.0. The page output cache API mainly refers to the HttpCachePolicy class.

   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.

CacheProfile NoStore = Duration Shared Location SqlDependency VaryByControl VaryByCustom VaryByHeader VaryByParam

@ OutputCache command code <% @ OutputCache= """True | False"= "# Ofseconds"= "True | False"= "Any | Client | Downstream | Server | None | ServerandClient"= "Database/table name pair | CommandNotification"= "Controlname"= "Browser | customstring"= "Headers"= "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 (in SQL Server 2005) is used with the CommandNotification value, 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 <% @ 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 <% @ 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 extends a method of programming to set the page output cache using the output cache API 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

Added methods for 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 (for definitions of these enumeration values, 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. 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.

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.