Introduction to the page caching feature of ASP.net 2.0

Source: Internet
Author: User
Tags bool httpcontext implement include instance method table name tostring valid
Asp.net| Cache | page

Page partial caching refers to parts of the output cache page, rather than caching the entire page content. There are two mechanisms for implementing page partial caching: One is to place the portion of the page that needs to be cached in a user control (. ascx file) and to set caching for the user control (the ASP.net page that contains the user control can be set or not set to cache). This is what is commonly called the "control cache." The essence of setting the control cache is to cache the user control for configuration. Mainly includes the following 3 methods: One is to use the @ OutputCache directive to set caching for the user control declaratively, and the second is to use the PartialCachingAttribute class in the code-behind file to set the user control cache Third, use the Controlcachepolicy class to programmatically specify user control cache settings. In addition, there is a method called "cache replacement." This method, in contrast to the control cache, sets a portion of the page to not be cached, so that, while the entire page is cached, the page is processed again when it is requested again, which is not set to the cached content.

  Using the @ OutputCache directive

The @ OutputCache directives for control caching and page output caching have similarities and differences. The common denominator is that they are set in the same way, with the @ OutputCache instruction string that contains the properties at the top of the file. The different points include the following two aspects: one is the control cache @ OutputCache directive is set in the user control file, and the page output cache @ OutputCache is set in the normal ASP.net file. The second is that the @ OutputCache directive cached by the control can only set 6 properties, Duration, Shared, SqlDependency, VaryByControl, VaryByCustom, and VaryByParam. As many as 10 properties are set in the @ OutputCache instruction string in the page output cache. These are the issues you need to be aware of when setting control caching. Here are some examples of setting control caching using the @ OutputCache directive, which focuses on attribute applications such as VaryByParam and VaryByControl.

The @ OutputCache directive in the user control sets the source code

<%@ OutputCache duration= "varybyparam=" CategoryID; Selectedid "%>

The above code sets the user control cache expiration time to 120 seconds and allows the CategoryID and Selectedid parameters to be used to change the cache. With the VaryByParam property setting, instances of multiple user controls may be stored in the server cache. For example, for a page that contains a user control, there may be a URL link as follows.

URL link for the page containing the user control

Http://localhost/mypage.aspx?categoryid=foo&selectedid=0
Http://localhost/mypage.aspx?categoryid=foo&selectedid=1

When you request a page with the URL address above, the two version of the user control cache instance is stored in the server cache because of the setting of the @ OutputCache directive in the control, especially the setting of the property VaryByParam.

The control cache setting supports the VaryByControl property in addition to the VaryByParam properties described above. The VaryByParam property changes the cache based on a name/value pair that is sent using post or get, while the VaryByControl property changes the cache by using the server control contained in the user control file. The following is the application sample code for the VaryByControl property.

The @ OutputCache directive in the user control sets the source code

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

The above code sets the cache validity period to 120 seconds and the page does not change with any get or post parameters (even if you do not use the VaryByParam property, you still need to explicitly declare the property in the @ OutputControl directive). If a user control contains a server control with an id attribute of "Category" (for example, a Drop-down box control), the cache stores the user control data according to the control's changes.

If the reader has mastered the @ OutputCache instruction setting method of the page output cache, the @ OutputCache instruction cached by the control will also be resolved, using only 6 of these attributes. However, there may be a question: if the ASP.net page and the user controls contained therein are set by the @ OutputCache directive, how should the cache run?

When encountering this problem, the following basic principles should be mastered: First, asp.net allows you to set the cache with the @ OutputCache directive in the user control of the page and page, and allows you to set different cache expiration values. The second is that if the page output cache expires longer than the user control output cache expiration time, the page's output cache duration takes precedence. For example, if the page output cache is set to 100 seconds, and the user control's output cache is set to 50 seconds, the entire page, including the user control, is stored in the output cache for 100 seconds, regardless of the user control's shorter time settings. Third, if the page output cache expiration time is shorter than the user control's output cache expiration time, the user control is cached until its expiration expires even if the remainder of the page is regenerated for a request. For example, if the page output cache is set to 50 seconds, and the user control output cache is set to 100 seconds, the user control expires once for the remainder of the page to expire two times.

  using the PartialCachingAttribute class

Use the PartialCachingAttribute class to set configuration content about the control cache in the code-behind file for the user control. Here you should focus on the 6 common properties of the PartialCachingAttribute class and the 4 kinds of constructors. 6 Common properties are duration, Shared, SqlDependency, VaryByControl, VaryByCustom, and VaryByParam. This is exactly the same as the 6 properties set by the control cache @ OutputCache directive as shown earlier, except in the same way that it is used. These 6 properties are not repeated here. The following highlights the 4 constructors of the PartialCachingAttribute class, which is important for using this class.

[Partialcaching (int duration)]

This is one of the most common formats. The parameter duration is an integer type to set the user control cache expiration time value. This parameter corresponds to the duration attribute in the @ OutputCache directive.

[Partialcaching (int duration, string varybyparams, String varybycontrols, String varybycustom)]

This format has more content. The parameter duration is the same as described above. The parameter varybyparams is a semicolon-delimited list of strings that can be used to change the output cache. This parameter corresponds to the VaryByParam attribute in the @ OutputCache directive. Parameter varybycontrols is a semicolon-delimited list of strings that are used to change the output cache and correspond to the VaryByControl attribute in the @ OutputCache directive. The parameter varybycustom is used to set any text that represents a custom output cache requirement, corresponding to the VaryByCustom attribute in the @ OutputCache directive.

[Partialcaching (int duration, string varybyparams, String VaryByControls, String varybycustom, BOOL shared)]

In this format, the parameters duration, VaryByParams, VaryByControls, and VaryByCustom are the same as those described above. Only parameter shared is newly added. A parameter shared value is a Boolean value that determines whether the user control output cache can be shared by multiple pages. The default value is False. When this parameter is set to True, the user control output cache can be shared by multiple pages, potentially saving a lot of memory.

[Partialcaching (int duration, string varybyparams, String VaryByControls, String VaryByCustom, String SqlDependency, BOOL shared)]

A new parameter SqlDependency is added to the above format. A database and table name used to set the SQL Server cache dependency functionality used by the user control cache entry. If multiple databases and table names are included, separate them with semicolons (;). When the value of this property changes, the cache entry expires. In addition, the database name must match the contents of the configuration section in the Web.config file.

The 6 properties and 4 constructors of the PartialCachingAttribute class are described above. The following is a typical example of how this class is applied. For example, using the PartialCachingAttribute class to set the cache expiration time for a user control (Newusercontrol.ascx file) is 20 seconds, as shown in the following code.

Setting up user control caching using the PartialCachingAttribute class implementation

[Partialcaching (20)]

public partial class Newusercontrol:usercontrol
{......}

The above code is stored in the NewUserControl.ascx.cs file. Newusercontrol is a user control class that inherits from the UserControl base class. When you use the PartialCachingAttribute class to set the user control cache, you must set "[Partialcaching (...)]" before the control class declaration. This snippet allows you to set the caching capabilities of the user control in detail. For example, the above code sets the cache validity time to 20 seconds. This is consistent with the Duration property value of 20 that sets instructions at the top of the Newusercontrol.ascx file.

Because the user control applies the PartialCachingAttribute class (or contains the @ OutputCache directive), the ASP.net parser generates an instance of the PartialCachingControl class to wrap the user control. It should be noted that there is a necessary condition for generating the PartialCachingControl class instance at this time, That is, the user control must be dynamically loaded by using the Templatecontrol.loadcontrol method, and the user control is inserted into the control hierarchy of the page, so that the PartialCachingControl class instance is generated. In general, you cannot use the PartialCachingControl class directly. Generating PartialCachingControl class instances can gain greater flexibility to set the user control cache at run time.

  using the Controlcachepolicy class

Controlcachepolicy is a new class in. NET Framework 2.0 that provides programmatic access to output-cache settings for user controls. The Controlcachepolicy class is similar to the HttpCachePolicy class described in the previous article. Only the objects accessed by the two are different. The HttpCachePolicy class is used to access the page output cache, while the Controlcachepolicy class is used to access the user cache.

Using the Controlcachepolicy class has the following considerations.

First, if you want to create a properly valid Controlcachepolicy class instance to set the control cache, Then you must access the Basepartialcachingcontrol.cachepolicy property of the PartialCachingControl class (Basepartialcachingcontrol is the base class for the PartialCachingControl Class) 。 In this process, you need to invoke the LoadControl method to dynamically load the user control so that you can get the user control instance wrapped for the PartialCachingControl class. The CachePolicy property is used to obtain the Controlcachepolicy instance. If you access the Usercontrol.cachepolicy property of a user control directly, you can obtain a valid Controlcachepolicy instance only if the user control is already wrapped by the Basepartialcachingcontrol control. If the user control is not wrapped, attempting to get the Controlcachepolicy instance through the CachePolicy property throws an exception because it does not have an associated basepartialcachingcontrol. To determine whether a user control instance supports caching (without generating an exception), you can check the Supportscaching property.

The second is that the Controlcachepolicy instance can be successfully operated only between the Init and PreRender phases of the control life cycle. If you modify the Controlcachepolicy object after the PreRender phase, ASP.net throws an exception because any changes made after the control is rendered cannot affect the cache settings (the control is cached in the render phase). The above describes the best way to create and manipulate controlcachepolicy instances in the Page_Init event handler.

Here's the first 6 properties of the Controlcachepolicy class, which are cached, Dependency, Duration, supportscaching, VaryByControl, and VaryByParams.

Cached property

Used to get or set a Boolean value that indicates whether the control caching feature is enabled in the user control. True indicates that the control caching feature is enabled or FALSE.

dependency property

Used to get or set a CacheDependency instance object that is associated with the output cache of the user control. The default value is null. When the CacheDependency instance object is invalidated, the output cache of the user control is removed from the cache.

Duration Property

Gets or sets a timespan structure that represents the valid time for the user control output cache. The default value is zero.

Supportscaching Property

This property gets a Boolean value that indicates whether the user control supports caching. A property value of TRUE indicates that the user control supports caching;

VaryByControl Property

Used to get or set a semicolon-delimited list of strings containing the server control ID property values declared in the user control. The output cache can be changed based on the value of this property.

VaryByParams Property

Used to get or set a semicolon-delimited list of strings. 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. The user control can change the output cache based on the property value.

In addition, the Controlcachepolicy class also includes 3 common methods, SetExpires, Setslidingexpiration, and SetVaryByCustom.

public void SetExpires (DateTime expirationtime);

Indicates that the user control output cache entry expires within a specified time. The Setslidingexpiration method that can be used with the parameter setting indicates that the user control output cache uses an adjustable expiration policy. If the parameter of the Setslidingexpiration method is set to False, the user control output cache uses an absolute expiration policy.

public void Setslidingexpiration (bool useslidingexpiration);

Indicates that the user control cache entry uses the sliding expiration policy, or the absolute expiration policy. When the parameter useslidingexpiration is set to True, the user control output cache uses the sliding expiration policy. Otherwise, use the absolute expiration policy.

public void SetVaryByCustom (string varybycustom);

Any text used to customize the output cache for a user control. If the property value is browser, the user control output 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 Global.asax file.

The following is a typical example of dynamically setting the user control cache expiration of 30 seconds and using an absolute expiration policy. The user control code-behind file source code is as follows.

Setting up user control caching using the PartialCachingAttribute class implementation (user control code-behind file)

[Partialcaching (100)]

public partial class Simplecontrol:usercontrol
{......}

As shown in the code above, the user control class name is SimpleControl and the default control cache expiration of 100 seconds is set using the PartialCachingAttribute class. The purpose of this setting is to implement the wrapper for the user control class using the PartialCachingAttribute class, otherwise, it is invalid to invoke the Controlcachepolicy instance obtained by the CachePolicy property in the ASP.net page. You can also use other methods to PartialCachingAttribute class wrappers on user controls, such as setting @ OutputCache directives.

The following is an enumeration of asp.net page file source code.

Setting up user control caching using the Controlcachepolicy class implementation (asp.net paging file)

<%@ Page language= "C #" debug= "true"%>
<%@ Reference control= "Simplecontrol.ascx"%>

void Page_Init (object sender, System.EventArgs e)
{
Dynamically loads the user control and returns the instance object of the PartialCachingControl

PartialCachingControl PCC = LoadControl ("Simplecontrol.ascx") as PartialCachingControl;

Get Controlcachepolicy instance by CachePolicy property

Controlcachepolicy cachesettings = PCC. CachePolicy;

If the user control's cache expiration setting is greater than 60 seconds, set the new expiration time to 30 seconds and set it to an absolute expiration policy

if (Cachesettings.duration > Timespan.fromseconds (60))
{
Set user control expiration and cache expiration policies
Cachesettings.setexpires (DateTime.Now.Add (Timespan.fromseconds (30)));
Cachesettings.setslidingexpiration (FALSE);
}
To add a user control to the page control hierarchy
Controls.Add (PCC);
}

The above code is part of a asp.net file source code that contains the user control Simplecontrol.ascx, primarily programmatically implementing settings for the output caching of user controls. During the entire implementation, the user control cache needs to be set up in the Page_Init event handler for the ASP.net page. First, dynamically load the SimpleControl using the Templatecontrol.loadcontrol method. ascx file. Because the user control SimpleControl ... Ascx has been packaged for the PartialCachingAttribute class (This step is critical), so the return object of the LoadControl method is not a null reference, but rather a partialcachingcontrol instance. Then, use the CachePolicy property of the PartialCachingControl instance object to get the Controlcachepolicy instance object. This object is used primarily to set settings for user control output caching. Next, use the SetExpires method and the Setslidingexpiration method with the parameter false to set the user control output cache to be valid for 30 seconds and set the cache to use an absolute expiration policy. Finally, use the Add method of the controls class to add a set of user controls to the page control hierarchy. In addition, the @ Reference directive is used to dynamically compile and link user control Simplecontrol.ascx.

  Implementing Cache Replacement

Asp. NET page contains both static content and dynamic content based on database data. Static content is usually not changed. Therefore, it is necessary to implement data caching for static content. However, the dynamic content that is based on the data is different. The data in the database may change all the time, so if caching the dynamic content can result in a problem that data cannot be updated in a timely manner. It is obviously impractical to use the control caching method described earlier in this issue, and it is very cumbersome and easy to make mistakes.

The essence of the problem described above is how to implement most of the cached page, without caching some fragments in the page. The ASP.net 2.0 provides cache-post replacement functionality. There are three ways to implement this feature: one is to use the substitution control declaratively, the other is to programmatically use the substitution control API, and the third is to use the control implicitly. The core of the first two methods is the substitution control, which is highlighted in this section, and the third method focuses only on the cached post-replacement functionality that is supported in the control's built-in, which is only briefly described in this section.

1. Substitution Control Application

To improve application performance, the entire ASP.net page may be cached, and a specific part of the page may need to be updated based on each request. For example, you might want to cache a large portion of a page, and you need to dynamically update information that is highly relevant to time or users on that page. In this case, it is recommended that you use the substitution control. The substitution control can specify portions of the page output cache that need to replace the control with dynamic content, that is, to allow output caching for an entire page, and then use the substitution control to specify portions of the page that are exempt from caching. The area that needs to be cached executes only once, then reads from the cache until the cache entry expires or is purged. The dynamic region, which is the part specified by the substitution control, is executed each time the page is requested. The substitution control provides a simplified solution for caching part of a page.

Substitution controls inherit from the control base class, whose declaration code looks like this:

Substitution control Declaration Code

As shown in the previous code, the substitution control has an important property ––––methodname property. This property is used to get or set the name of the method that is invoked for the callback when the substitution control executes. This method is special and must conform to the following 3 criteria: This method must be defined as a static method; This method must accept parameters of type HttpContext; This method must return a string of values.

Under run conditions, the substitution control automatically invokes the method defined by the MethodName property. The string returned by the method is the content to display on the position of the substitution control in the page. If the page has all the cached output set up, the page will run and cache its output on the first request. For subsequent requests, the cache will be completed, and the Code on the page will not run. The substitution control and its associated methods are executed every time the request is made, and the dynamic content represented by the control is automatically updated.

Note the following 3 points: first, the substitution control cannot access other controls on the page, that is, you cannot check or change the values of other controls. However, the code can indeed use the arguments passed to it to access the current page context. The second is to include the substitution control in the user control contained in the cached page. However, you cannot place the substitution control in an output-cached user control. Three is that the substitution control does not render any markup, and its location depends entirely on the return string of the method that is defined.

The following is an example of using the substitution control to implement a cache-after substitution feature. The example effect is shown in Figure 3.

Figure 3 Replacing the sample effect diagram after caching

The application includes two time display. The first time display uses the substitution control to implement the cache-after substitution feature, so each time you click the Refresh Page button, it displays the current latest time. The second time display has the page output cache applied, so its display time is only updated when the data expires.

The application Default.aspx file source code is shown below.

Default.aspx File Source code

<%@ Page language= "C #" autoeventwireup= "true" codefile= "Default.aspx.cs" inherits= "_default"%>
<%@ OutputCache duration= "5" varybyparam= "None"%>
! DOCTYPE HTML PUBLIC "-//w3c//dtd XHTML 1.1//en" "Http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"
Sample 12-2


public static string GetCurrentDateTime (HttpContext context)
{
return DateTime.Now.ToString ();
}












As shown in the bold code, the page mainly includes substitution, label, and Button controls. The label control is set to display the time value in the Page_Load event handler. In addition, a static method GetCurrentDateTime is implemented, the method parameter is HttpContext type, the return value is string, and the return content is the current time. Setting the page output cache expiration of 5 seconds at the top of the code through the @ OutputCache directive means that the entire page data has a caching feature applied. Therefore, the value of the time displayed by the label control comes from the data cache. This time value does not change as the page is refreshed, and updates occur only if the data expires. The MethodName property value of the substitution control is getcurrentdatetime. The control displays content from the return value of the GetCurrentDateTime method. It is particularly important that although the page has the output caching feature set, the ASP when the page refreshes. The net execution engine still has to rerun the substitution control and displays the method return value specified by the MethodName property value on the page, so the current time value is displayed.

2. Substitution Control API Application

The previous section describes the application of using the substitution control declaratively to implement cache replacement. This section still describes another implementation approach around implementing the cache-after substitution feature. The core of this approach is to use the substitution control APIs programmatically to implement cache substitution, which is more flexible than the method of using substitution controls declaratively.

The Substitution control API includes a key WriteSubstitution method that comes from the HttpResponse class with the following syntax code:

Syntax of the WriteSubstitution method
public void WriteSubstitution (HttpResponseSubstitutionCallback callback)

As shown above, the WriteSubstitution method has only one parameter httpresponsesubstitutioncallback. The parameter is a delegate with the syntax code as follows:

HttpResponseSubstitutionCallback delegate Syntax
Public delegate string HttpResponseSubstitutionCallback (HttpContext Context)

As shown in the previous code, the HttpResponseSubstitutionCallback delegate defines a method that has two characteristics: one is that the return value must be a string, and the second is that the argument has only one and is a HttpContext type. The

above describes the syntax of the WriteSubstitution method and its parameters, which is the key to implementing cache substitution using the WriteSubstitution method.

When the specified response region is dynamically generated for the cached output response, as required programmatically, You can pass the name of a method (that is, the callback method) as an argument (HttpResponseSubstitutionCallback) to the WriteSubstitution method in the page code. The WriteSubstitution method can then use the callback method and display the return value of the callback method as an alternative to the given position. In this process, the declaration of the callback method is critical, not only to take a single HttpContext parameter, but also to return a string. It is important to note that the callback method must be thread safe, either as a Web page for a container or as a static method in a user control, or as a static or instance method on any other object. Thus, the advantage of using the WriteSubstitution method is that you can call the method of any object, not just the static method of the page or UserControl object.

When the page is first requested, WriteSubstitution performs the following steps: Invoking the HttpResponseSubstitutionCallback delegate to generate output; Adding alternate buffer data to the response. The buffer retains the delegate (called for future requests) and the first output in step one, and finally, the client caching capability is dropped from "public"?????? ?o?? Low to server-only so that the page will not be cached on the client, making sure that subsequent requests for that page will recall the delegate and generate dynamic content. On subsequent requests, the cache module intercepts the incoming request and retrieves the associated storage buffer. When a replacement buffer is written, the delegate is invoked to generate a new output that is written to the response.

The following is an example of an application of the WriteSubstitution method that accomplishes the same function as the example shown in Figure 12-3. The difference is the way of implementation. The previous example uses the substitution control, which uses the WriteSubstitution method of the substitution control API. Application default.aspx file part of the source code is as follows:

Default.aspx file part source code

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

Sample 12-3


public static string GetCurrentDateTime (HttpContext context)
{
return DateTime.Now.ToString ();
}


......

<% response.writesubstitution (New HttpResponseSubstitutionCallback (GetCurrentDateTime)); %>

......


As shown in the bold code, the page uses the @ OutputCache directive to set output caching, which has a configuration data cache expiration of 5 seconds. However, not all page content is cached and part of the content is not cached. The content that does not participate in the cache is the return string that is obtained and displayed by calling the Response.WriteSubstitution method in code, showing the current time. It is important to note that the parameter of the Response.WriteSubstitution method must be a HttpResponseSubstitutionCallback delegate instance. In this case, the delegate defines a method that is GetCurrentDateTime, is a static method, and the parameter is a HttpContext type, and the return value is a string type.

  AdRotator the control's cache-after substitution

is a control that directly supports caching substitution functionality. If you place a control on a page, the parent page is presented with its own ad-specific advertisement on each request, whether or not it is cached. This caching model is useful, for example, if the page contains static content, such as news stories, and controls that display advertisements. News reports will not change, which means they can be cached. However, the application requires that a new advertisement be displayed each time the page is requested. Because the control supports cache-behind substitution directly, a new advertisement is rendered when the page is postback, regardless of whether the page is cached.



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.