不禁用ChildActionOnly输出缓存

时间:2019-09-17 13:10:51

标签: c# asp.net-mvc outputcache

我在标有[ChildActionOnly]的控制器中执行以下操作:

[OutputCache(Duration = 3600)]
public PartialViewResult SideNavigation()
{
    SideNavigationModel model = _sideNavigationFactory.GetSideNavigation();

    if (model != null)
    {
        return PartialView(model);
    }

    return default(PartialViewResult);
}

当我用以下命令调用时,哪个工作正常?

@Html.Action("SideNavigation", "Template") 

在我的主模板中。但是我注意到,当我更新侧面导航的cshtml文件时,即使在web.config中禁用了输出缓存,该文件也不会在网页上更新:

<outputCache enableOutputCache="false">

如果我更改了主模板,则将打开,它将更新,但模板的导航部分不会更新。这是预期的行为吗?如果可以,是否只有在启用输出缓存后才可以输出缓存?

2 个答案:

答案 0 :(得分:1)

using System.Web.Configuration;
using System.Web.Mvc;

namespace Mvc.Filters
{
    public class ExtendedOutputCacheAttribute : OutputCacheAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!web.config.caching.disabled) // just read the right config setting somewhere 
            {
               base.OnActionExecuting(filterContext);
            }
        }
    }
}

答案 1 :(得分:0)

由于this answer和Laurent提供的答案的结合,我使用自定义属性提出了以下解决方案:

TimeoutException

然后可以使用以下命令将其添加到子动作控制器中:

public class ChildActionOutputCacheAttribute : OutputCacheAttribute
{
    private const string _cachingSection = "system.web/caching/";
    private const string _outputCacheSection = "outputCache";
    private const string _profileSection = "outputCacheSettings";
    private bool _profileEnabled;

    public ChildActionOutputCacheAttribute(string cacheProfile)
    {
        // get output cache section of web config
        OutputCacheSection settings = (OutputCacheSection)WebConfigurationManager.GetSection($"{_cachingSection}{_outputCacheSection}");

        // check section exists and caching is enabled
        if (settings != null && settings.EnableOutputCache)
        {
            // if caching enabled, get profile
            OutputCacheSettingsSection profileSettings = (OutputCacheSettingsSection)WebConfigurationManager.GetSection($"{_cachingSection}{_profileSection}");
            OutputCacheProfile profile = profileSettings.OutputCacheProfiles[cacheProfile];

            if (profile != null && profile.Enabled)
            {
                // if profile exits set profile params
                Duration = profile.Duration;
                VaryByParam = profile.VaryByParam;
                VaryByCustom = profile.VaryByCustom;

                _profileEnabled = true;           // set profile enable to true as output cache is turned on and there is a profile
            }
        }
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (_profileEnabled)
        {
            // only run this if caching has been set and is enabled
            base.OnActionExecuting(filterContext);
        }
    }
}

如果您的web.config中包含以下部分:

[ChildActionOutputCache(CacheProfile.Long)]