Caching ChildActions using cache profiles won't work?

前端 未结 5 1630
粉色の甜心
粉色の甜心 2020-12-03 08:13

I\'m trying to use cache profiles for caching child actions in my mvc application, but I get an exception: Duration must be a positive number.

My web.config looks li

5条回答
  •  忘掉有多难
    2020-12-03 08:29

    That works for me.

    public class ChildActionOutputCacheAttribute : OutputCacheAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.IsChildAction && !string.IsNullOrWhiteSpace(CacheProfile))
            {
                lock (this.GetType())
                {
                    if (!string.IsNullOrWhiteSpace(CacheProfile))
                    {
                        // OutputCacheAttribute for child actions only supports
                        // Duration, VaryByCustom, and VaryByParam values.
                        var outputCache = (OutputCacheSettingsSection)WebConfigurationManager.GetSection("system.web/caching/outputCacheSettings");
                        var profile = outputCache.OutputCacheProfiles[CacheProfile];
                        if (profile.Enabled)
                        {
                            Duration = profile.Duration > 0 ? profile.Duration : Duration;
                            VaryByCustom = string.IsNullOrWhiteSpace(profile.VaryByCustom)
                                ? VaryByCustom : profile.VaryByCustom;
                            VaryByParam = string.IsNullOrWhiteSpace(profile.VaryByParam)
                                ? VaryByParam : profile.VaryByParam;
                        }
                        CacheProfile = null;
                    }
                }
            }
            base.OnActionExecuting(filterContext);
        }
    }
    

提交回复
热议问题