【问题标题】:Has something changed in caching data in ASP.NET-MVC3?在 ASP.NET-MVC3 中缓存数据有什么变化吗?
【发布时间】:2011-06-29 11:34:16
【问题描述】:

我需要在我的 MVC3 项目中使用应用程序级缓存。

我想在控制器中使用这样的东西:

using System.Web.Caching;    

protected IMyStuff GetStuff(string stuffkey)
{
    var ret = Cache[stuffkey];
    if (ret == null)
    {
        ret = LoadStuffFromDB(stuffkey);
        Cache[stuffkey] = ret;
    }
    return (IMyStuff)ret;
}

这会失败,因为 Cache["foo"] 没有编译为“System.Web.Caching.Cache 是一个‘类型’,但用作‘变量’”。

我看到Cache是​​一个类,但是网上有很多例子在控制器中像Session["asdf"]一样像属性一样使用。

我做错了什么?

【问题讨论】:

    标签: asp.net-mvc-3 caching


    【解决方案1】:

    控制器中有一个名为Session 的属性,但没有名为Cache 的属性。 您应该使用HttpRuntime.Cache 静态属性来获取Cache 对象。 例如:

    using System.Web.Caching;    
    
    protected IMyStuff GetStuff(string stuffkey)
    {
        var ret = HttpRuntime.Cache[stuffkey];
        if (ret == null)
        {
            ret = LoadStuffFromDB(stuffkey);
            HttpRuntime.Cache[stuffkey] = ret;
        }
        return (IMyStuff)ret;
    }
    

    【讨论】:

    • 其实你的例子和我的一个字一个字是一样的,但答案对我有帮助。
    【解决方案2】:

    MVC 中有更新的数据缓存方法 像 - [输出缓存(持续时间=3)] 您也可以在 web.config 文件中指定它 如此处所示: http://dotnetcodr.com/2013/02/07/caching-infrastructure-in-mvc4-with-c-caching-controller-actions/ 如果您在 MVC 中进行开发,这将更加高效且易于使用

    • 但是,如果您希望使用以前的方法进行缓存,您可以考虑 System.Web.HttpContext.Current.Cache["variable"] = datasetresultlistObjectResult IE。, System.Web.HttpContext.Current.Cache["POSSEData"] = MyDevObjBO.GetListOfObjects();

    然后根据需要重新分配: IE。, grdViewStuff.DataSource = (List)System.Web.HttpContext.Current.Cache["POSSEData"];

    【讨论】:

    • 你用“较新的方法”指的是什么?
    猜你喜欢
    • 2011-11-17
    • 1970-01-01
    • 2012-01-19
    • 2019-05-23
    • 2015-04-15
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    相关资源
    最近更新 更多