【问题标题】:MVC3 custom outputcacheMVC3 自定义输出缓存
【发布时间】:2011-04-08 03:44:03
【问题描述】:
我想在我的应用程序中使用缓存,但我返回的数据是特定于登录用户的。当我需要因用户而异时,我不能使用任何开箱即用的缓存规则。
有人能指出我创建自定义缓存属性的正确方向吗?从控制器中,我可以从Thread.CurrentPrincipal.Identity; 或我在控制器构造函数_user 中初始化的私有控制器成员访问用户
谢谢。
【问题讨论】:
标签:
asp.net-mvc
asp.net-mvc-2
asp.net-mvc-3
【解决方案1】:
您可以使用 VaryByCustom。在 Global.asax 中覆盖 GetVaryByCustomString 方法:
public override string GetVaryByCustomString(HttpContext context, string arg)
{
if (arg == "IsLoggedIn")
{
if (context.Request.Cookies["anon"] != null)
{
if (context.Request.Cookies["anon"].Value == "false")
{
return "auth";
}
else
{
return "anon";
}
}
else
{
return "anon";
}
}
else
{
return base.GetVaryByCustomString(context, arg);
}
}
然后使用 OutputCache 属性:
[OutputCache(CacheProfile = "MyProfile")]
public ActionResult Index()
{
return View();
}
在 web.config 中:
<caching>
<outputcachesettings>
<outputcacheprofiles>
<clear />
<add varybycustom="IsLoggedIn" varybyparam="*" duration="86400" name="MyProfile" />
</outputcacheprofiles>
</outputcachesettings>
</caching>
【解决方案3】:
您应该使用OutputCache.VaryByCustom Property 来指定自定义变化字符串。要使用它,您应该覆盖 Global.asax 中的方法
public override string GetVaryByCustomString(HttpContext context, string arg)
{
if(arg.ToLower() == "currentuser")
{
//return UserName;
}
return base.GetVaryByCustomString(context, arg);
}