OutputCache cache optimizes ASP. NET code improves Web page performance

Source: Internet
Author: User
Tags microsoft sql server 2005

    • For Web pages written by ASP, using caching is a very important and commonly used optimization technique, which can greatly reduce the load pressure on the server and optimize the performance of these web pages, compared with any other function using the. NET Framework. Using caching appropriately can better improve the performance of your site. At the same time, the page accelerated display also played a big role.

      OutputCache
      Declaratively controls the output caching policy for user controls that are contained in an ASP. NET page or page.

      Syntax :

      <%@ OutputCache duration= "#ofseconds"
      location= "any | Client | downstream | Server | None | ServerAndClient "
      shared= "True | False "
      Varybycontrol= "ControlName"
      varybycustom= "Browser | CustomString "
      varybyheader= "Headers"
      Varybyparam= "ParameterName"
      varybycontentencoding= "Encodings"
      cacheprofile= "Cache Profile Name | ‘‘"
      Nostore= "true | False
      sqldependency= "database/table Name pair | CommandNotification "
      Providername= "Provider Name"
      %>

      parameter explanation :

      A The
      Parameters Description Note
      Duration

      The time, in seconds, that the page or user control is cached. Setting this attribute on a page or user control establishes an expiration policy for an HTTP response from an object and automatically caches the output of the page or user control.

      This attribute is required. If this property is not included, a parser error occurs.

      Unless you location=none, you can not add this property, and the rest of the time is required.

      Location

      One of the OutputCacheLocation enumeration values. The default value is any.
      Location when set to none, the rest of the settings will not work;
      The any--page is cached in the browser, proxy server, and Web server side;
      client--cache in Browser;
      The downstream--page is cached in the browser and on any proxy server side;
      none--page does not cache;
      The serverandclient--page is cached on the browser and Web server side.

      The @ OutputCache directive contained in a user control (. ascx file) does not support this attribute.
      CacheProfile The name of the cache setting associated with the page. This is an optional attribute, and the default value is an empty string ("").

      The @ OutputCache directive contained in a user control (. ascx file) does not support this attribute. 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 below the outputCacheSettings section. If this name does not match the configuration file, an exception is thrown.

      reference :CacheProfile instances

      Nostore A Boolean value that determines whether the level two storage of sensitive information is blocked. The @ OutputCache directive contained in a user control (. ascx file) does not support this attribute. Setting this attribute to true is equivalent to executing the following code during a request:
      Response.Cache.SetNoStore ();
      ProviderName A string value that identifies the custom output-cache provider to use. This property is supported only in user controls (. ascx files). It is not supported by the @ OutputCache directive contained in an ASP. NET page (. aspx file).
      Shared A Boolean value that determines whether the user control output can be shared by multiple pages. The default value is False. The @ OutputCache directive contained in an ASP. NET page (. aspx file) does not support this attribute.
      SqlDependency A string value that identifies a set of database/table name pairs that are dependent on the output cache of the page or control. Note that the SqlCacheDependency class monitors the tables in the database that the output cache depends on, so when you update items in the table, the items are removed from the cache when you use table-based polling. If you use notifications with a value of CommandNotification (in Microsoft SQL Server 2005), you will eventually use the SqlDependency class to register query notifications with the SQL Server 2005 server.

      The CommandNotification value of the SqlDependency attribute is only valid in the Web page (. aspx). The user control can only use table-based polling for the @ OutputCache directive.

      reference :sqldependency and SqlCacheDependency cache usage and specific steps

      VaryByCustom Any text that represents the custom output-cache requirement. If the attribute is assigned a value of 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 GetVaryByCustomString method in the application's Global.asax file.
       varybyheader

      Semicolon-delimited list of HTTP headers that are used to make the output cache vary. When this attribute is set to multiple headers, the output cache contains a different version of the requested document for each specified header combination. The
      accept-language--represents the list of human languages that the user wants most in the request page, and the
      user-agent--represents the type of request page device, and
      cookie--represents the Cookie entry for the browser created under the current domain name. The

      Setting VaryByHeader attribute will enable caching of entries in all HTTP version 1.1 caches, not just in the ASP. The @ OutputCache directive in the user control does not support this attribute.
      For example: Set varybyheader= "Accept-language".
      When a Web site has multiple language versions, it can be cached for each language.

       varybyparam semicolon-delimited list of strings used to make the output cache vary. By default, these strings correspond to query string values sent using the GET method attribute, or parameters that are sent using the POST method. When the attribute is set to multiple parameters, the output cache contains a different version of the requested document for each combination of specified parameters. Possible values include none, an asterisk (*), and any valid query string or POST parameter name.

      This attribute or VaryByControl attribute is required when using the @ OutputCache directive on ASP. If it is not included, a parser error occurs. If you do not want to change the contents of the cache by specifying parameters, set the value to none. If you want to change the output cache with all of the parameter values, set the attribute to an asterisk (*).
      For example:
      If the command is set to:
      <%@ OutputCache duration= "  varybyparam=" ProductType "%>
      When request path bitauto.com/ Test.aspx? When producttype=1 occurs, the cache is established when the value of ProductType becomes 2 o'clock, a new cache is created, but the original cache does not expire within the validity period. The equivalent of a different version of the cache is created for different producttype values. If familiar. NET data cache, it is similar to the following usage.
      Cache.Add ("ProductType1", Cachedobject)
      Cache.Add ("ProductType2", Cachedobject)

      VaryByControl A semicolon-delimited list of strings used to alter 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 attribute or VaryByParam attribute is required when you use the @ OutputCache directive on both the ASP and user controls.
      For example: different cache output depending on the selected value of the page drop-down list control
      <%@ OutputCache duration= "varybycontrol=" Droptest "%>"
      VaryByContentEncodings A semicolon-delimited list of strings used to change the output cache. Use the VaryByContentEncodings attribute with the accept-encoding header to determine how different content encodings get cached responses.

      OutputCache Example :

      The following code example demonstrates how to set the duration of the output cache for a page or user control.

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

      The next code example shows how to instruct the output cache to cache them by the location of the page or user control, and to count the form parameters based on the form's POST method or query string. Each HTTP request received with a different location or count parameter (or both) is cached for 10 seconds. Any subsequent request with the same parameter value will be satisfied from the cache until the input cache period is exceeded.

      <%@ OutputCache duration= "Ten" varybyparam= "Location;count"%>

      Application Examples :

      ▲ Figure 1 Stop the cached

      Figure 2 Performing the cache

      As shown in 1, the application initially shows the time to stop the cache execution. When the user refreshes the page, the time value changes to show the current latest time.

      2, when you click the cache time hyperlink, the page is redirected to another page. At this point, the time the page is displayed is cached and the data expires at 5 seconds. If you continue to refresh the page, the time value changes every 5 seconds.

      The example in this section has two key points. One 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" >
      <script language= "C #" runat= "Server" >
      void Page_Load (object sender, EventArgs e)
      {//settings store cached data on the server only
      Response.Cache.SetCacheability (Httpcacheability.server);
      String temp_location = request.querystring["Location"];
      If location is empty, it is not cached, otherwise the cache is executed according to the @ OutputCache directive declaration
      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 cache time:" + DateTime.Now.ToString ();
      }
      }
      </script>
      <title> Example 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" > Set page output cache </legend><br/>
      <center><asp:label id= "Label1" runat= "Server" cssclass= "Commontext" ></asp:Label></center> <br/>
      <a href= "default.aspx?location=beijing" class= "Littlemaintitle" > Cache time </a><br/>
      </fieldset>
      </div>
      </form>
      </body>

      As shown in the code above, the @outputcache instruction at the head of the code sets the duration and VaryByParam properties, which indicate 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, using the SetCacheability method to set the data cache must be stored on the server, and then get the location parameter value of the QueryString, and finally, based on the location parameter value to judge. If the location parameter value is NULL, the Setnoservercaching method is called to stop all server caches for the current response and to display the current time value. Although the @ OutputCache directive configures the page output cache, the page output caching feature is not performed. If the location parameter value is not empty, the current time value is displayed directly. In this case, the configuration content of the @ OutputCache instruction is executed.

      <%@ OutputCache nostore= "True" duration= "" "location=" any "varybycontrol=" OC "varybycustom=" Browser "VaryByHeader = "Headers" varybyparam= "None"%>

      Precautions for using OutputCache

      When using the ASP. NET cache, you should be aware of the following considerations. First, do not cache too many items. There is a memory overhead for each item being cached. Do not cache items that are easy to recalculate and seldom used. Second, the validity period of assigning a cache item is not too short. Items that expire soon cause unnecessary turnover in the cache and cause additional code cleanup and garbage collection work. You can monitor the turnover caused by the expiration of an item in the cache by using the cache total turnover rate (overall buffer flow) performance counter associated with the ASP. Applications performance object. A high turnover rate may indicate a problem, especially when an item is removed before it expires. (This situation is sometimes referred to as memory pressure.) )

      The

      can consider using caching techniques to put static, small changes, or infrequently changing content that needs to be loaded dynamically into the control.

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.