如何以编程方式为特定用户控件使用输出缓存?

时间:2012-03-24 10:30:53

标签: c# asp.net

我想以编程方式将输出缓存应用于特定控件。但是,当我使用此代码时,它会将所有页面和其他用户控件存储在缓存输出中。

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

1 个答案:

答案 0 :(得分:7)

HttpResponse.Cache属性获取整个网页的缓存策略(例如到期时间,隐私设置和各种条款)。这就是上面的代码缓存整个网页的原因。

要缓存您的用户控件,您可以使用PartialCachingAttribute。是你的控件支持片段缓存。然后通过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);
        }
    }
}

可以在MSDN上的Caching Portions of an ASP.NET Page articke中找到更多信息。