ASP.NET MVC 3缓存或不缓存操作策略
我有一个动作,比如说/Foo/Bar,在这个动作中有一个GET参数, get_cached,定义我们是要获取缓存值还是“实时” 这是通过以下代码实现的:ASP.NET MVC 3缓存或不缓存操作策略,asp.net,asp.net-mvc,caching,Asp.net,Asp.net Mvc,Caching,我有一个动作,比如说/Foo/Bar,在这个动作中有一个GET参数, get_cached,定义我们是要获取缓存值还是“实时” 这是通过以下代码实现的: public ActionResult Bar() { var useCache = Request.Params["get_cached"] == "1" ? true : false; if (useCache) { return RedirectToAction("BarCached");
public ActionResult Bar()
{
var useCache = Request.Params["get_cached"] == "1" ? true : false;
if (useCache)
{
return RedirectToAction("BarCached");
}
else
{
return RedirectToAction("BarRealTime");
}
}
[OutputCache(Duration = 100, VaryByParam = "*")]
public ActionResult BarCached()
{
return Content("mystuff_cached");
}
public ActionResult BarRealTime()
{
return Content("mystuff_realtime");
}
这段代码没有问题,除了url将显示为BarCached或BarrelTime之外,我将只获得Bar(主操作名称)
我尝试将RedirectToAction更改为完整的方法名,如下所示:
return this.BarCached()
但这会禁用缓存功能
那么,如何使用此方法上的OutputCache定义(BarCached上的OutputCache)从方法(render BarCached from Bar)呈现ActionResult代码呢
提前感谢。在asp.net中,ResolveRequestCache(OutputCache所依赖的)在请求通过身份验证后立即发生。在上面的示例中,当您使用“Bar”时,使用输出缓存已经太迟了,正如您所说的this.BarCached()
无法识别缓存属性
如果您的问题是生成“mystuff”
的任何对象的性能,您是否可以将该调用的结果保存到应用程序缓存中,并将其返回到Bar()
方法中,而不是重定向到Action
对象中
我知道的解决方案不多,但希望同样有用。我最后使用了
System.Web.Caching
命名空间,它是asp.net MVC的基本缓存处理程序。
我可以使用System.Web.HttpContext.Current.cache
使用它,我存储了“BarCached”的ActionResult,然后我可以使用下面这样的方式获得缓存功能:
return this.BarCached()
向缓存中添加一个值
System.Web.HttpContext.Current.Cache.Insert(
"mykey",
"myvalue",
null,
DateTime.Now.AddSeconds(expirationInSeconds),
System.Web.Caching.Cache.NoSlidingExpiration
);
并从缓存中获取值
var myvalue = System.Web.HttpContext.Current.Cache.Get("mykey")
是的,你澄清了我的问题。