缓存在IIS7上显示旧值,而不是在调试服务器上显示

时间:2012-01-31 19:41:47

标签: asp.net-mvc-3 caching static

我有一个非常标准的MVC3应用程序。我正在尝试将一些应用程序范围(非用户范围)的数据存储在缓存中(在本例中为Theme对象/名称)。在调试时(在与Visual Studio集成的开发服务器上),如果我调用SwitchTheme,我会立即看到新主题。在IIS7上,无论缓存什么主题,都会保持缓存状态;它没有更新到新主题。

修改:部分代码:

    public static Theme CurrentTheme { get {
        Theme currentTheme = HttpContext.Current.Cache[CURRENT_THEME] as Theme;

        if (currentTheme == null)
        {
            string themeName = DEFAULT_THEME;
            try
            {
                WebsiteSetting ws = WebsiteSetting.First(w => w.Key == WebsiteSetting.CURRENT_THEME);

                if (ws != null && !string.IsNullOrEmpty(ws.Value))
                {
                    themeName = ws.Value;
                }
            }
            catch (Exception e)
            {
                // DB not inited, or we're installing, or something broke.
                // Don't panic, just use the default.
            }

            // Sets HttpContext.Current.Cache[CURRENT_THEME] = new themeName)
            Theme.SwitchTo(themeName);
            currentTheme = HttpContext.Current.Cache[CURRENT_THEME] as Theme;

        }

        return currentTheme;
    } }

public static void SwitchTo(string name)
    {
        HttpContext.Current.Cache.Insert(CURRENT_THEME, new Theme(name), null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(30));

        // Persist change to the DB.
        // But don't do this if we didn't install the application yet.
        try
        {
            WebsiteSetting themeSetting = WebsiteSetting.First(w => w.Key == WebsiteSetting.CURRENT_THEME);
            if (themeSetting != null)
            {
                themeSetting.Value = name;
                themeSetting.Save();
            }
            // No "else"; if it's not there, we're installing, or Health Check will take care of it.
        }
        catch (Exception e)
        {
            // DB not inited or install not complete. No worries, mate.
        }
    }

我不确定问题出在哪里。我正在调用相同的方法并更新缓存;但是IIS7只是向我展示了旧版本。

我可以在IIS中禁用输出缓存,但这不是我想要做的。这看起来像是一个hacky work-at。

3 个答案:

答案 0 :(得分:1)

如果没有代码示例,很难知道您的问题是什么。为了提供一些帮助,以下是我经常在我的应用程序中设置缓存的方法:

    public static void SetCache(string key, object value) {
        if (value != null) {
            HttpRuntime.Cache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(30));
        }
    }

答案 1 :(得分:1)

仅当您手动执行此操作或应用程序域(或应用程序池)因任何原因重置时,才会重置HTTP缓存。你确定在这种情况下不会发生这种情况吗?一般来说,任何全局静态变量也会在相同的情况下保存在内存中。

有很多原因导致应用程序池可能在任何给定点重置,例如更改web.config文件等。我建议检查您的情况是否发生这种情况。

顺便说一下,输出缓存是另一回事,尽管它在内存中的维护方式大致相同。

答案 2 :(得分:0)

鉴于这只发生在IIS7上,当没有禁用输出缓存时,这似乎很可能是一个IIS7错误。严重。

是否与解决方案无关。您需要做的是找到一些使缓存无效的手动过程,例如触摸web.config文件。

但要注意:这样做会消除缓存(如你所料),还会消除所有静态变量(作为副作用)。不知道这是否是另一个错误,我不知道;但就我而言,这足以解决问题。

相关问题