Compartir a través de


How to: Set Expiration Values for ASP.NET Page Caching

To cause a page to be added to the output cache, you establish an expiration policy for that page. You can do this declaratively or programmatically.

To set output-cache expirations for a page declaratively

  • Include an @ OutputCache directive in the ASP.NET page (.aspx file) whose response you want to cache. Set the Duration attribute to a positive numeric value, and set the VaryByParam attribute to a value.

    NoteNote

    The @ OutputCache directive sets the Cache-Control header to Any by default.

    For example, the following @ OutputCache directive sets the page's expiration to 60 seconds:

    <%@ OutputCache Duration="60" VaryByParam="None" %>
    
    NoteNote

    You must include a VaryByParam attribute when using the @ OutputCache directive or a parser error will occur. If you do not want to use the functionality offered by the VaryByParam attribute, set its value to "None". For more information, see Caching Multiple Versions of a Page.

To set output-cache expirations for a page programmatically

  • In the page's code, set the expiration policy for the page on the Cache property of the Response object.

    NoteNote

    If you set expirations for a page programmatically, you must set the Cache-Control header for the cached page as well. To do so, call the SetCacheability method and pass it the HttpCacheability enumeration value Public.

    The following code example sets the same cache policy as the @ OutputCache directive does in the preceding procedure.

    Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
    Response.Cache.SetCacheability(HttpCacheability.Public);
    Response.Cache.SetValidUntilExpires(true);
    
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(60))
    Response.Cache.SetCacheability(HttpCacheability.Public)
    Response.Cache.SetValidUntilExpires(True)
    

    When the cached page expires, the subsequent request for the page causes a dynamically generated response. This response page is cached for the specified duration.

See Also

Tasks

How to: Set the Cacheability of an ASP.NET Page Declaratively
How to: Set a Page's Cacheability Programmatically

Concepts

Caching ASP.NET Pages
Setting the Cacheability of a Page