使用缓存配置文件缓存ChildActions不起作用?

fre*_*nky 17 asp.net-mvc caching

我正在尝试使用缓存配置文件缓存我的mvc应用程序中的子操作,但我得到一个例外:持续时间必须是正数.

我的web.config看起来像这样:

<caching>
      <outputCache enableOutputCache="true" />
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="TopCategories" duration="3600" enabled="true" varyByParam="none" />
        </outputCacheProfiles>
      </outputCacheSettings>
</caching>
Run Code Online (Sandbox Code Playgroud)

而我的孩子的动作是这样的:

[ChildActionOnly]
[OutputCache(CacheProfile = "TopCategories")]
//[OutputCache(Duration = 60)]
public PartialViewResult TopCategories()
{
    //...
    return PartialView();
}
Run Code Online (Sandbox Code Playgroud)

我只是打电话给一个视图 @Html.RenderAction("TopCategories", "Category")

但是我收到一个错误:Exception Details:System.InvalidOperationException:Duration必须是一个正数.

如果我不使用缓存配置文件,它的工作原理.知道问题是什么?

Gre*_*rts 17

我做了一些挖掘相关问题并查看mvc 3源代码,他们肯定不支持除DurationVaryByParam之外的任何属性.它们当前实现的主要缺陷是,如果您不提供其中任何一个,您将收到一个异常,告诉您提供该异常,而不是例外,说明您尝试使用的内容不受支持.另一个主要问题是,即使你关闭了web.config中的缓存,它们也会缓存,这看起来非常蹩脚而且不对.

我遇到的最大问题是它们使用的是在视图和部分视图中都有效的相同属性,但实际上它应该是2个不同的属性,因为局部视图非常有限并且行为有很多不同,至少在它的当前实施.

  • 这是一篇很好的文章解释了这个问题:http://www.dotnetcurry.com/ShowArticle.aspx?ID = 665 (2认同)

Pab*_*meo 17

我解决此问题得到了通过创建一个自定义OutputCache属性,手动加载Duration,VarByCustomVarByParam从配置文件:

public class ChildActionOutputCacheAttribute : OutputCacheAttribute
{
    public ChildActionOutputCacheAttribute(string cacheProfile)
    {
        var settings = (OutputCacheSettingsSection)WebConfigurationManager.GetSection("system.web/caching/outputCacheSettings");
        var profile = settings.OutputCacheProfiles[cacheProfile];
        Duration = profile.Duration;
        VaryByParam = profile.VaryByParam;
        VaryByCustom = profile.VaryByCustom;
    }
}
Run Code Online (Sandbox Code Playgroud)

这种方法的优点是您仍然可以将所有配置文件保存在web.config中的一个位置.

  • 工作得很好 - 我必须覆盖`OnActionExecuting`,并且只有在web.config中启用了缓存配置文件时才调用`base.OnActionExecuting`.否则,在设置`enabled ="false"`时会重新出现可怕的"持续时间"错误. (3认同)