다음을 통해 공유


Setting Expirations for Page Caching

To add a page to the output cache, you must establish an expiration policy for that page. You can do this declaratively with the @ OutputCache directive or programmatically using the HttpCachePolicy.SetExpires method. The @ OutputCache directive sets the Cache-Control header to Public by default.

If you set expirations for a page programmatically, you must set the Cache-Control header for the cached page as well. Use the HttpCachePolicy.SetCacheability method to set the HttpCacheability enumeration to Public.

To set output-cache expirations for a page declaratively

  • Include an @ OutputCache directive in the page (.aspx file) whose response you want to store in the output cache. The directive must include a Duration attribute, with a positive numeric value, and a VaryByParam attribute. The following @ OutputCache directive sets the page's expiration to 60 seconds.

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

    Note   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 about using the VaryByParam attribute, see Caching Multiple Versions of a Page.

To set output-cache expirations for a page programmatically

  • In the page's code-declaration block, or in the code-behind class for the page, include code that sets the expiration policy for the page by using Response.Cache syntax. The following example sets expirations for the page as the @ OutputCache directive does in the previous procedure.

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

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

See Also

Caching ASP.NET Pages | HttpCacheability Enumeration | Caching Page Output with Cache Key Dependencies | HttpCachePolicy Class | HttpResponse Class | @ OutputCache Directive