【问题标题】:Page.Cache vs. HttpContext.Current.CachePage.Cache 与 HttpContext.Current.Cache
【发布时间】:2014-05-21 16:31:47
【问题描述】:

我阅读了一个 Web 应用程序的源代码,发现它使用缓存对象 (Web.Caching.Cache) 来缓存数据。在代码隐藏文件(aspx.cs 文件)中,它使用 Page.Cache 来获取 Cache,而在其他类定义文件中,它使用 HttpContext.Current.Cache 来获取 Cache。我想知道为什么它不使用相同的选项来获取缓存。有人可以解释 Page.Cache 和 HttpContext.Current.Cache 之间的区别吗?为什么要为上面的每个上下文使用每个。我可以在上面的两个上下文中使用 Page.Cache 或 HttpContext.Current.Cache 吗? 提前致谢。

【问题讨论】:

    标签: asp.net caching


    【解决方案1】:

    没有区别,前者使用当前页面实例,它是Cache property,后者通过HttpContext.Current.Cache 使用static 方法,在没有页面实例的静态方法中也可以工作。

    两者都指向同一个应用程序缓存。

    因此您可以通过Page 获得Cache,例如Page_Load

    protected void Page_load(Object sender, EventArgs e)
    {
        System.Web.Caching.Cache cache = this.Cache;
    }
    

    或通过HttpContext.Current 使用静态方法(在HttpContext 中使用):

    static void Foo()
    {
        var context = HttpContext.Current;
        if (context != null)
        {
            System.Web.Caching.Cache cache = context.Cache;
        }
    }
    

    【讨论】:

    • 感谢您的回答。这对我很有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多