Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use output cache programmatically for a particular user control?

Tags:

c#

asp.net

I want to apply output cache programmatically to a particular control. But when I'm using this code, it stores all the page and other user control in cache output.

    if (Session["id"] != null)
    {            
        Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
        Response.Cache.SetCacheability(HttpCacheability.Public);
        Response.Cache.SetValidUntilExpires(true); 
     }
like image 247
pargan Avatar asked Dec 14 '25 16:12

pargan


1 Answers

HttpResponse.Cache property gets caching policy (such as expiration time, privacy settings, and vary clauses) of a whole web page. That's why the code above caches the whole web page.

To cache your user control you could use PartialCachingAttribute. Is says that your control supports fragment caching. And then programmatically change the necessary caching properties through UserControl.CachePolicy property:

[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);
        }
    }
}

Additional information could be found in the Caching Portions of an ASP.NET Page articke on MSDN.

like image 176
Oleks Avatar answered Dec 16 '25 06:12

Oleks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!