ASP. NET cache-multiple versions of cache pages

Source: Internet
Author: User
Tags form post http post

Sometimes, you may want to cache a page, but create different versions for the page based on the request. For example, the page may have different outputs based on the values passed in the query string.

ASP. NET allows multiple versions of the same page to be cached in the output cache. The output cache may vary depending on the following factors:

  • The query string in the initial request (http get.

  • The http post value ).

  • The HTTP header passed with the request.

  • The main version number of the browser that sends the request.

  • Custom string on this page. In this case, you can create custom code in the Global. asax file to specify the cache behavior of the page.

You can use either of the following two methods to cache multiple versions of the page output: Use the attribute of the @ OutputCache command to declare the version, or use the attributes and methods of the HttpCachePolicy class to program the version.

@ OutputCache Commands include four attributes that can be used to cache multiple versions output by pages:

  • The VaryByParam attribute can be used to make the cache output vary with query strings.

    Returns a comma-separated list of query strings or form POST parameters. This list is used by the output cache to change cache items.
    If this attribute is set to multiple parameters, the output cache contains different versions of the requested document for each specified parameter. Possible values include "none", "*", and any valid query string or POST parameter names.

    Note:

    When used for caching purposes, ASP. NET treats the query string values with the same key/value pairs or the sent values of the form as the same, regardless of the order in which parameters are transmitted. However, for caching purposes, parameter names are case-sensitive. ASP. NET caches pages of different versions for both the parameter names and parameter values in uppercase and lowercase.

    Multiple versions of the page output are cached using parameters declared

    1. Include the @ OutputCache command on the ASP. NET page.DurationAttribute.DurationAttribute is required and must be set to an integer greater than zero.

    2. In the @ OutputCache command, includingVaryByParamAttribute, and set its value to the name of the query string or form sending parameter that you want to change with the page.

      The following code example caches the page for 60 seconds and specifies thatCityQuery the output versions of the string value or the format sending parameter cache page.

      Copy code

      <%@ OutputCache Duration="60" VaryByParam="City" %>

      Note:

      To change the output cache based on multiple parameters, include a list of parameter names separated by semicolons. If you want to change the cache based on all parameter values, SetVaryByParamSet attribute to asterisk (*). The following code example demonstrates how to useCityAndZipCodeParameter Change page output.

    Use parameters to programmatically cache multiple versions of page output
    1. InPage_LoadThe SetCacheability and SetExpires methods are called for the Cache attribute of the Response object.

    2. Specify the parameter nameResponseThe variable of the VaryByParams attribute of the object, and set this attributeTrue.

      The following code example demonstrates thatZipWhen a request with a parameter value arrives at the server, how does one cache multiple versions of the page.

      Response. Cache. SetExpires (DateTime. Now. AddMinutes (1.0 ));
      Response. Cache. SetCacheability (HttpCacheability. Public );
      Response. Cache. SetValidUntilExpires (true );
      Response. Cache. VaryByParams ["Zip"] = true;

      Note:

      If you want to change the cached content based on multiple parameters, set it multiple times.VaryByParamsAttribute. To change the cached content based on all header values, set the VaryByHeader attribute to asterisk (*).

  • The VaryByControl attribute allows the cache output to vary with control values.

    Gets or sets control identifiers separated by one group number. These identifiers are contained on the current page or user control and used to change the current cache item.
    A semicolon-separated string list used to change the output cache of items.VaryByControlProperty is set to a fully qualified control identifier, where the identifier is a concatenation of the Control ID, starting from the top-level parent control and separated by the dollar sign ($.

  • The VaryByHeader attribute can be used to make the cache output vary with the HTTP header of the request.

    Gets or sets a set of comma-separated header names used to change cache items. The header name identifies the HTTP header associated with the request.
    If this attribute is set to multiple headers, the output cache contains different versions of the requested document for each specified header.

    Cache each version of a page in a declarative manner based on the HTTP header value
    1. On the ASP. NET page, the @ OutputCache command contains the required Duration and VaryByParam or VaryByControl attributes. You must setDurationSet the property to an integer greater than zero. If you want to cache only by HTTP header value, you mustVaryByParamSet the property to "None ".

    2. The @ OutputCache command contains the VaryByHeader attribute and sets the value to the name of the HTTP header to be used as the basis for changing the cached content.

      The following example caches the page for 60 seconds andAccept-LanguageSet the version of the page to be cached for the value passed by the HTTP header:

      Copy code

      <%@ OutputCache Duration="60" VaryByParam="None" VaryByHeader="Accept-Language" %>

      Note:

      To change the cached content based on multiple headers, use semicolon (;) as the separator to include the list of header names. If you want to change the cached content based on all header values, SetVaryByHeaderSet attribute to asterisk (*).

    Caches each version of a page programmatically Based on the HTTP header value
    1. InPage_LoadThe SetCacheability and SetExpires methods are called for the Cache attribute of the page Response object.

    2. Set the HTTP header value in the VaryByHeaders attributeTrue.

      The following code example demonstrates howAccept-LanguageThe HTTP header value request caches multiple versions of a page for one minute.

      Protected void Page_Load (object sender, EventArgs e)
      {
      Response. Cache. SetExpires (DateTime. Now. AddMinutes (1d ));
      Response. Cache. SetCacheability (HttpCacheability. Public );
      Response. Cache. SetValidUntilExpires (true );
      }

      Note:

      To change the cached content based on multiple headersVaryByHeadersSet multiple values in the property. If you want to change the cached content according to all headers, SetVaryByHeaders["VaryByUnspecifiedParameters"] setTrue.

  • The VaryByCustom attribute can be used to make the cache output vary by browser type or custom string.

    Obtains the list of custom strings used by the output cache to change the cache items. If you specify this attribute as "browser", the cache items change with the browser type and main version number. If you enter a custom string, you must re-write HttpApplication. GetVaryByCustomString in the Global. asax file of the application.

    Note:

    The main version and browser type information are transmitted in the current request through the MajorVersion attribute of the HttpBrowserCapabilities object. For more information, see How to: Detect browser types in ASP. NET web pages.

    Cache multiple versions of pages in a declarative manner based on browser types

    1. The ASP. NET page contains a @ OutputCache command with the required Duration and VaryByParam or VaryByControl attributes. You must setDurationSet the property to an integer greater than zero. If you want to cache only by browser typeVaryByParamSet the property to "None ".

    2. In the @ OutputCache command, include the VaryByCustom attribute and set it to "browser ".

      The following example causes the page to be cached continuously for up to 10 seconds. The output varies with the browser type.

      Copy code

      <%@ OutputCache Duration="10" VaryByParam="None" VaryByCustom="browser" %>

    Multiple pages are cached programmatically Based on the browser type.
    1. In the Page code, call the SetExpires and SetCacheability methods for the Cache attribute of the page Response attribute.

    2. Call the SetVaryByCustom method and pass the value "browser" in the custom parameter ".

      The following code example shows how to keep multiple pages cached for one minute. The output varies according to the browser type of the request.

      Protected void Page_Load (object sender, EventArgs e)
      {
      Response. Cache. SetExpires (DateTime. Now. AddMinutes (1d ));
      Response. Cache. SetCacheability (HttpCacheability. Public );
      Response. Cache. SetValidUntilExpires (true );
      Response. Cache. SetVaryByCustom ("browser ");
      }

      In addition to different output cache Behaviors Based on browser types and parameters, you can also cache multiple versions of page output based on different strings returned by the method you define.

      When caching pages based on custom strings, you must first specify the identifier of the custom string to be used. Create a method in the Global. asax file of the application. This method accepts this identifier and returns a value as the basis for different output cache behaviors.

      Caches multiple output versions based on custom strings.
      1. The ASP. NET page contains the @ OutputCache Command, which has the required Duration and VaryByParam attributes. You must setDurationSet the property to an integer greater than zero. If you do not want to useVaryByParamAttribute, you must set its value to "NONE ".

      2. To set a custom string in declaration mode, include the varybycustom attribute in the @ outputcache command, and set this attribute as the string you want to use as the basis for different output cache behaviors.

        The following command is based on the custom string"Minorversion"Change page output.

        <%@ OutputCache Duration="10" VaryByParam="None" VaryByCustom="minorversion" %>

      3. To set a custom string programmatically, call the setvarybycustom method and pass the custom string to it.

        The following code example shows how to set a custom string to "minorversion ".

        C #

        Response. cache. setvarybycustom ("minorversion ");

        Note:

        If you try to set a custom string programmatically or declared, you will receive InvalidOperationException. You need to select one of the methods.

        In the global. asax file of the application, override the getvarybycustomstring method to specify the output cache behavior of the custom string.
      4. The method to be overwritten is accepted inVaryByCustomAttribute orSetVaryByCustomThe string set in the method, as itsArgParameters. For example, some pages may be cached Based on the next version of the requested browser. For these pages, you canVaryByCustomSet the attribute to "minorversion ". ThenGetVaryByCustomStringYou can check the ARG parameter accordingArgIf the parameter value is "minorversion", different strings are returned.

        The following code example demonstrates a global. asax file, whereGetVaryByCustomStringMethod is overwritten.

        C # copy code

        <%@ Application language="C#" %>            <script runat="server">            public override string GetVaryByCustomString(HttpContext context,            string arg)            {            if(arg == "minorversion")            {            return "Version=" +            context.Request.Browser.MinorVersion.ToString();            }            return base.GetVaryByCustomString(context, arg);            }            </script>            

  • Note:

    You must includeVaryByParamAttribute orVaryByControlAttribute. However, if you do not need to make the cache output vary by control value or parameter, you can define the valueNoneOfVaryByParam.

HttpCachePolicyClass provides two attributes and a method. You can use them to specify the same cache configuration as the cache configuration that can be set in Declaration. You can use the VaryByParams and VaryByHeaders attributes to specify the query string parameters and header names as the basis for cache policy changes. You can use the SetVaryByCustom method to define the custom string to be used as the basis for output cache changes.

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.