Asp. NET page Caching

Source: Internet
Author: User

The entire contents of the static page are 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 have to go through the page processing life cycle again. This can reduce request response time and improve application performance. Obviously, the page output cache is useful for not having to update data frequently, and it takes a lot of time and resources to compile the generated pages. It is not applicable for pages that are frequently updated with data. By default, ASP. NET 2.0 enables the page output caching feature, but does not cache the output of any response. The developer must pass the settings so that some page responses become part of the cache.

There are two ways to set the page output cache: One is to use the @ OutputCache directive, and the other is to use the page output caching API. The @ OutputCache directive has been present 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, the general need for page output caching can be achieved. The @ OutputCache directive declares the header of the user control contained in an ASP. NET page or page. This is a convenient way to implement a page's output caching strategy with just a few simple property settings. The @ OutputCache directive declaration code is as follows.


@ 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, in the @ OutputCache directive, there are 10 properties, which are CacheProfile, Nostore, Duration, GKFX, location, SqlDependency, VaryByControl, VaryByCustom, VaryByHeader and VaryByParam. These properties 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

Used to define the name of the cache settings associated with the page. is an optional property and the default value is a null character (""). It is important to note that the @ OutputCache directive contained in the user control does not support this property. When you specify this property in a page, the property value must match the name of one of the available items in the outputCacheProfiles element under the <outputCacheSettings> configuration section of the Web. config file. If this name does not match the configuration file, an exception is thrown.

Nostore

This property defines a Boolean value that determines whether to block level two storage of sensitive information. It is important to note that the @ OutputCache directive contained in the user control does not support this property. Setting this property to true is equivalent to executing the code during the request "Response.Cache.SetNoStore ();".

Duration

Used to set the page or user control cache time. Unit is seconds. By setting this property, you can establish an expiration policy for the HTTP response from the object and automatically cache the page or user control output. It is important to note that the Duration property is required, otherwise it will cause a parser error.

Shared

This property defines a Boolean value that determines whether the user control output can be shared by more than one page. The default value is False. Note that this property is not supported by the @ OutputCache directive contained in the ASP.

Location

Used to specify the location of the output cache entry. Its property values are OutputCacheLocation enumeration values, which are any, Client, downstream, None, server, and ServerAndClient. The default value is any, which indicates that the output cache is available for all requests, including the client browser, the proxy server, or the server that is processing the request. It is important to note that the @ OutputCache directive contained in the user control does not support this property.

SqlDependency

This property identifies a set of string values for a database/table name pair, and the output cache of a 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, using table-based polling will remove those items from the cache. When the notification (in SQL Server 2005) is used with the CommandNotification value, the SqlDependency class is eventually used to register the query notification with the SQL Server 2005 server. In addition, the CommandNotification value of the SqlDependency property is valid only in ASP. Control can only use table-based polling 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 property 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 the property value is given as 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 make the output cache vary. 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 just the ASP. 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 make the output cache vary. By default, these strings correspond to the query string values sent with the Get method property, or to the parameters sent with the Post method. When the 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 cache is an ASP. It is also required for a user control unless the VaryByControl property has been included in the user control's @ OutputCache directive. If it is not included, a parser error occurs. If you do not need to make the cached content 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 code using the @outputcache directive.


Example code for using @ OutputCache 1


<%@ OutputCache duration= "" "varybyparam=" None "%>


The above example is a basic application of the @ OutputCache directive, which indicates that the page output cache is valid for 100 seconds, and the page does not change with any get or post parameters. Requests that are received when the page is still cached are serviced by 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.


Example code for using @ OutputCache 2


<%@ OutputCache duration= "varybyparam=" Location;firstname "%>"


The above @ OutputCache instruction 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, if the client request is "http://localhost/default.aspx?location=beijing", then the page will be processed as a cache.

   using the page output caching API

The above describes the use of the @ OutputCache instruction to implement the various settings for the output cache. This method is simple and easy, and is favored by developers. In addition, ASP. NET 2.0 also inherits from ASP. NET 1.x and extends a method of programming page output caching using the output caching API. The core of the method is to call System.Web.HttpCachePolicy. This class primarily contains methods for setting cache-specific HTTP headers and for controlling the output cache of ASP. The HttpCachePolicy class in the. NET Framework 2.0 has been expanded and developed in comparison to the HttpCachePolicy class in the. NET Framework 1.x. Some important methods, such as Setomitvarstar method, are added. Because of the numerous HttpCachePolicy methods, the following is a brief description of some common methods.

SetExpires method

Used to set the absolute time for cache expiration. Its argument is an instance of the Datatime class that represents the absolute time of expiration.

Setlastmodified method

The last-modified HTTP header used to set the page. The last-modified HTTP header indicates when 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 the Datatime class.

Setslidingexpiration method

This method sets the cache expiration from the absolute time to the adjustable time. Its argument 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 option that adds an expiration header to all output sets relative to the current time. When the parameter 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 cache policy by subsequent modules or secondary requests.

Setomitvarystar method

The new method for ASP. NET 2.0. Used to specify whether the response should contain the vary:* header when differentiated by parameters. The method parameter is a Boolean value that indicates true if HttpCachePolicy does not use the * value for its VaryByHeaders property, or false.

SetCacheability method

The Cache-control HTTP header used to set the page. This header is used to control how documents are cached on the network. The method has two overloads, the difference being the parameter. The parameters of an overloaded method are 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 parameter is the HttpCacheability enumeration value, and the other is a string that represents the cache control extension added to the header. It is important to note that the field extension is valid only when used with private or nocache directives. If incompatible directives and extensions are combined, this method throws an invalid parameter exception.

The following is an example of how the HttpCachePolicy class of the page cache API is used.


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 cache policy. The data type of the property is HttpCachePolicy. You can get the HttpCachePolicy instance by calling Response.Cache to implement 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 for cache expiration to be 6 o'clock in the afternoon the same day.

  Page output Cache app

The above two subsections describe the use of the @ OutputCache directive and API to set the page output caching feature. In fact, both methods have advantages, using the @ OutputCache instruction method is relatively concise, but less flexible. Using the API approach, you can dynamically modify the cache configuration at runtime to handle more complex requirements.

Asp. NET page Caching

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.