How do I use the output cache programmatically for a specific custom control?

I want to apply the output cache programmatically to a specific control. But when I use this code, it saves the entire page and other custom control in the cache.

    if (Session["id"] != null)
    {            
        Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
        Response.Cache.SetCacheability(HttpCacheability.Public);
        Response.Cache.SetValidUntilExpires(true); 
     }

      

+3


source to share


1 answer


HttpResponse.Cache

the property gets the caching policy (such as expiration times, privacy settings, and various offers) of the entire web page. This is why the above code caches the entire web page.

To cache a custom control, you can use PartialCachingAttribute

. Says your control supports fragment caching. And then programmatically change the required caching properties using the property UserControl.CachePolicy

:



[PartialCaching(0)]
public partial class MyControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["id"] != null)
        {            
            this.CachePolicy.Duration = TimeSpan.FromSeconds(60);
        }
    }
}

      

For more information, see Cache Portions of an ASP.NET Page on MSDN.

+7


source







All Articles