如何以编程方式禁用ASP.NET MVC中的应用程序的OutputCache
问题描述:
如果web.config中的system.web.compilation
设置设置为debug="true"
,我希望OutputCache
功能被禁用。如何以编程方式禁用ASP.NET MVC中的应用程序的OutputCache
我可以成功地通过调用我的Global.asax的Application_Start()
这种方法来访问这个值:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
CompilationSection configSection = (CompilationSection)ConfigurationManager.GetSection("system.web/compilation");
if (configSection?.Debug == true)
{
filters.Add(new OutputCacheAttribute()
{
VaryByParam = "*",
Duration = 0,
NoStore = true
});
}
}
的问题是,在我的控制器有任何端点OutputCache
明确设置将不使用全局过滤器,这是建立。
[OutputCache(CacheProfile = "Month")]
[HttpGet]
public ViewResult contact()
{
return View();
}
这里就是那“月”的个人资料在我的web.config中定义:
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="Month" duration="2592000" location="Any" varyByParam="*" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
我需要能够抵消使用的明确定义的OutputCache配置文件,如“月”,当我在调试模式。我怎样才能做到这一点?
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="Month" duration="0" location="Any" varyByParam="*" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
当你的应用程序是内置的调试配置你不会有任何缓存:
答
实施改造@返回的答案可能是最直接的解决方案,为想要的标准使用情况下工作调试时禁用所有缓存。但是,因为它不是一个程序化的解决方案,所以我想出了一种在代码中完成所有工作的方法,这也适用于更高级的用例。
首先,我们要捕获应用程序启动时是否处于调试模式。我们将它存储在一个全局变量中以保持速度。
public static class GlobalVariables
{
public static bool IsDebuggingEnabled = false;
}
然后在Global.asax代码的Application_Start
方法,写入全局属性。现在
protected void Application_Start()
{
SetGlobalVariables();
}
private void SetGlobalVariables()
{
CompilationSection configSection = (CompilationSection)ConfigurationManager
.GetSection("system.web/compilation");
if (configSection?.Debug == true)
{
GlobalVariables.IsDebuggingEnabled = true;
}
}
我们将创建自己的类用于缓存,将从OutputCacheAttribute
继承。
public class DynamicOutputCacheAttribute : OutputCacheAttribute
{
public DynamicOutputCacheAttribute()
{
if (GlobalVariables.IsDebuggingEnabled)
{
this.VaryByParam = "*";
this.Duration = 0;
this.NoStore = true;
}
}
}
现在,当您装饰您的控制器端点缓存,只需使用新的属性,而不是[OutputCache]
。
// you can use CacheProfiles or manually pass in the arguments, it doesn't matter.
// either way, no caching will take place if the app was launched with debugging
[DynamicOutputCache(CacheProfile = "Month")]
public ViewResult contact()
{
return View();
}