c# - 如何在 asp.net 中使用 System.Web.Caching?

标签 c# asp.net caching asp.net-4.5

我有一个看起来像这样的类:

using System.Collections.Generic;
using System.Web.Caching;

public static class MyCache
{
    private static string cacheKey = "mykey";

    public static Dictionary<string, bool> GetCacheValue(bool bypassCache)
    {
        var settings = Cache[cacheKey] as Dictionary<string, bool>; // error on this line

        // ...etc...

        return settings
    }
}

我遇到的问题是无法编译。编译器说 Cache 不能像我这样使用。消息如下:

'System.Web.Caching.Cache' is a 'type' but is used like a 'variable'

这让我很困惑。我用谷歌搜索了 ASP.NET Cache API 并找到了许多以这种方式使用 Cache 的示例。这是其中一个示例:

// http://www.4guysfromrolla.com/articles/100902-1.aspx
value = Cache("key")

      - or -

value = Cache.Get("key")

当我尝试使用 Cache.Get() 时,我收到另一个错误,指出它不是静态方法。

显然我需要初始化一个 Cache 的实例。这是使用此 API 的正确方法吗?后续问题是,缓存信息是否跨实例持久存在?

感谢您的帮助。

最佳答案

System.Web.Caching.Cache 是一个类 - 您会看到人们使用名为 Cache 的属性,它是 实例>System.Web.Caching.Cache。如果您在为您提供 Cache 属性的类之外使用它,请使用 System.Web.HttpRuntime.Cache 访问它:

var settings = System.Web.HttpRuntime.Cache[cacheKey] as Dictionary<string, bool>;

关于c# - 如何在 asp.net 中使用 System.Web.Caching?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19054137/

相关文章:

c# - 在不读取整个文件的情况下获取图像尺寸

c# - 条件或对 Linq-to-entities 没有影响?

javascript - 由 javascript 更改时回发时丢失的值

HTTP 缓存 : What if different http proxies cache different versions of the same content?

http - 为什么浏览器不能缓存带有 Cache-Control HTTP header 的资源?

c# - 从 SOAP 消息中提取 SOAP 主体

c# - 如何使用 .net 编译器 API 检查 IDataReader 是否已关闭

asp.net - 使用 IIS7.5 在 64 位 Windows 上运行 x86 Asp.net 应用程序时出现问题

c# - GridView 在显示模式下显示,但不在浏览器中显示 ASP.NET C#

mysql - mysql memcached ndb 集群中如何进行更新