How to: Cache Versions of a Page Using HTTP Headers

ASP.NET allows you to cache multiple versions of a page depending on the value of an HTTP header that you specify. You can specify caching by a single header, multiple headers, or all headers passed to your application when the page is requested.

To cache versions of a page declaratively based on HTTP header values

  1. In the ASP.NET page, include an @ OutputCache directive with the required Duration and VaryByParam or VaryByControl attributes. The Duration attribute must be set to an integer greater than zero. If you want to cache only by HTTP header values, you must set the VaryByParam attribute to "None".

  2. In the @ OutputCache directive, include the VaryByHeader attribute and set its value to the name of the HTTP header that you want to vary the cache content by.

    The following example caches the page for 60 seconds and sets versions of a page to be cached based on the value passed with the Accept-Language HTTP header:

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

    If you want to vary the cached content by multiple headers, include a list of header names separated by semicolons (;). If you want to vary the cached content by all header values, set the VaryByHeader attribute to an asterisk (*).

To cache versions of a page programmatically based on an HTTP header value

  1. In the page's Page_Load method, call the SetCacheability and SetExpires methods on the Cache property of the page's Response object.

  2. Set the value for the HTTP header in the VaryByHeaders property to true.

    The following code example shows how to cache multiple versions of a page for one minute for requests with different values for the Accept-Language HTTP header.

    protected void Page_Load(object sender, EventArgs e)
        Response.Cache.VaryByHeaders["Accept-Language"] = true;

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Response.Cache.VaryByHeaders("Accept-Language") = true
    End Sub

    If you want to vary the cached content by multiple headers, you need to set multiple values in the VaryByHeaders property. If you want to vary by all headers, set VaryByHeaders["VaryByUnspecifiedParameters"] to true.

See Also

Community Additions