我想以编程方式将输出缓存应用于特定控件。但是,当我使用此代码时,它会将所有页面和其他用户控件存储在缓存输出中。
if (Session["id"] != null)
{
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);
}
答案 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中找到更多信息。