ASP.NET MVC 3缓存或不缓存动作策略

时间:2013-02-12 14:03:45

标签: 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");
    }
    else
    {
        return RedirectToAction("BarRealTime");
    }
}

[OutputCache(Duration = 100, VaryByParam = "*")]
public ActionResult BarCached()
{
    return Content("mystuff_cached");
}
public ActionResult BarRealTime()
{
    return Content("mystuff_realtime");
}

此代码没问题,除了网址将显示为 BarCached BarRealTime ,我只会获得Bar(主要操作名称)。

我尝试将RedirectToAction更改为完整的方法名称,如下所示:

return this.BarCached()

但这会禁用缓存功能!

那么,如何使用此方法上的OutputCache定义(BarCached上的OutputCache)从方法(从Bar渲染BarCached)呈现ActionResult代码?

先谢谢。

2 个答案:

答案 0 :(得分:1)

在asp.net pipeline中,ResolveRequestCache(OutputCache所依赖的)在请求通过身份验证后发生。在上面的示例中,当您使用“Bar”时,使用输出缓存为时已晚,正如您所说,this.BarCached()无法识别缓存属性。

如果问题是生成"mystuff_"生成的问题,您是否只能将该调用的结果保存到应用程序缓存中并将其返回到Bar()方法而不是RedirectToAction对象?

我所知道的解决方案并不多,但希望同样有用。

答案 1 :(得分:0)

我结束使用System.Web.Caching命名空间,它是asp.net MVC的基本缓存处理程序。 我可以使用System.Web.HttpContext.Current.Cache

访问Asp.NET MVC的缓存存储库

使用它,我存储" BarCached"的ActionResult。然后我可以按照我想要的方式获取缓存功能:

向缓存添加值

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")
相关问题