fra*_*lic 12 asp.net caching outputcache
我在用户控件的基类上使用PartialCaching属性.
我希望缓存的控件根据控件实例上设置的属性而变化.
例如:
<mycontrols:control1 runat="server" param1="10" param2="20" />
Run Code Online (Sandbox Code Playgroud)
...输出将与具有不同属性的控件实例分开缓存:
<mycontrols:control1 runat="server" param1="15" param2="20" />
Run Code Online (Sandbox Code Playgroud)
...此控件也将单独缓存:
<mycontrols:control1 runat="server" param1="10" param2="25" />
Run Code Online (Sandbox Code Playgroud)
但是,如果两个单独页面上的两个控件实例具有相同的 param1和param2属性,我希望它们作为一个对象进行缓存(以便共享缓存控件).
可以使用PartialCaching属性实现上述用例吗?我会使用什么设置?varyByControl?
此外,是否可以在运行时使缓存持续时间变量?
谢谢.
Ras*_*dit 22
要回答你的第一个Q,我先告诉你,你的问题本身就有答案;)."共享"...是的,这是关键字:)要在所有页面中为用户控件创建缓存中的单个实例,请在@OutputCache指令中设置Shared ='true'.这应该在用户控制级别设置,即在ascx页面中.
要基于用户控件属性缓存用户控件,应在PartialCachingAttribute的varyByControls部分中指定属性的完全限定名称.如果有多个属性应该用分号分隔.
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="WebUserControl.ascx.cs"
Inherits="UC_WebUserControl" %>
<%@ OutputCache Duration="60"
VaryByControl="UC_WebUserControl.param1;UC_WebUserControl.param2"
VaryByParam="none" Shared="true" %>
Run Code Online (Sandbox Code Playgroud)
或者您还可以包含用户控件的PartialCache属性:
[PartialCaching(60, null, "UC_WebUserControl.param1;UC_WebUserControl.param2", null, true)]
public partial class UC_WebUserControl : System.Web.UI.UserControl
{
public string param1 { get; set; }
public string param2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
或者在两个值的组合上缓存控件的另一种方法是:
[PartialCaching(60, null, "UC_WebUserControl.BothParams", null, true)]
public partial class UC_WebUserControl : System.Web.UI.UserControl
{
public string param1 { get; set; }
public string param2 { get; set; }
public string BothParams
{
get { return String.Concat(param1, param2); }
}
}
Run Code Online (Sandbox Code Playgroud)
最后一个参数(true)指定共享.持续时间由60指定.请参阅如何:基于参数缓存用户控件的多个版本链接
要回答第二个问题,要在运行时为用户控件变量设置缓存持续时间,可以通过两种方式完成:
在后面的用户控制代码中分配它:
[PartialCaching(60, null, "UC_WebUserControl.BothParams", null, true)]
public partial class WebUserControl1 : System.Web.UI.UserControl
{
...
protected void Page_Load(object sender, EventArgs e)
{
this.CachePolicy.Duration = new TimeSpan(0, 0, 60);
}
}
Run Code Online (Sandbox Code Playgroud)您可以使用用户控件的ID在引用用户控件的页面后面的代码中分配它.
例如,如果aspx上的用户控件是:
<mycontrols:control1 ID="ucControl1" runat="server" param1="15" param2="20" />
Run Code Online (Sandbox Code Playgroud)
那么在aspx的代码背后,你应该写:
this.ucControl1.CachePolicy.Duration = new TimeSpan(0, 0, 60);
Run Code Online (Sandbox Code Playgroud)
仅供参考,如果用户控件和页面都被缓存:如果页面输出缓存持续时间小于用户控件的持续时间,则用户控件将被缓存,直到其持续时间已到期,即使在页面的其余部分重新生成后也是如此请求.例如,如果页面输出缓存设置为50秒并且用户控件的输出缓存设置为100秒,则用户控件每两次到期一次,页面的其余部分将过期.
归档时间: |
|
查看次数: |
9783 次 |
最近记录: |