我想以编程方式将输出缓存应用于特定控件。但是当我使用这段代码时,它会将所有页面和其他用户控件存储在缓存输出中。
if (Session["id"] != null)
{
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);
}
最佳答案
HttpResponse.Cache
property 获取整个网页的缓存策略(如过期时间、隐私设置和 vary 子句)。这就是上面的代码缓存整个网页的原因。
要缓存您的用户控件,您可以使用 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);
}
}
}
更多信息可以在 Caching Portions of an ASP.NET Page 中找到MSDN 上的文章。
关于c# - 如何以编程方式为特定用户控件使用输出缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9850980/