通过使用C#指令在ASP.NET MVC应用程序中启用"调试模式"

mar*_*are 8 c# asp.net-mvc c-preprocessor

我在ASP.NET MVC控制器中的操作装饰有许多这样的属性

    [OutputCache(Duration = 86400, Location = OutputCacheLocation.Client,
        VaryByParam = "jsPath;ServerHost")]
    [CompressFilter]
    public JavaScriptResult GetPendingJavaScript(string jsPath, string serverHost)
Run Code Online (Sandbox Code Playgroud)

我想做的是将它包装在像#if和#endif这样的东西中,并在我的web.config文件中设置DebugMode.当此设置设置为true时,应忽略装饰属性 - 我想启用调试模式,并且在调试模式下不应进行压缩和缓存.

所以基本上就像评论那些装饰属性(我现在正在做什么,并厌倦了它):

    //[OutputCache(Duration = 86400, Location = OutputCacheLocation.Client,
    //    VaryByParam = "jsPath;ServerHost")]
    //[CompressFilter]
Run Code Online (Sandbox Code Playgroud)

显然#if和#endif使用定义的(#define)C#符号,我找不到任何可以用于其他类型条件的示例(如web.config值等).

帮助赞赏

Dan*_*son 2

相反,我将使用Web 部署项目以及web.config.

我会将每个组件的 web.config 分成两个文件。例如,对于您的输出缓存将分为outputcache.dev.configoutputcache.live.config。您应该输入配置源作为开发配置文件。

您的 dev.config 基本上会告诉您的应用程序您不想缓存运行 ( enableOutputCache="false")。

然后,当您运行部署项目时,您可以设置将 dev.config 字符串替换为 live.config。

有关 configSource 和 Web 部署项目的更多讨论

至于您的 CompressFilter 问题...好吧,我只需在您的配置文件中添加一个应用程序设置值即可。分割配置文件后,您将拥有appsettings.dev.config, 和appsettings.live.config. 在你的开发中,你会有类似的东西:

<add key="InLiveMode" value="false" />
Run Code Online (Sandbox Code Playgroud)

在你的 live.config 中,是的,你已经猜到了:

<add key="InLiveMode" value="true" />
Run Code Online (Sandbox Code Playgroud)

然后,当您使用该属性时,您可以简单地针对 InLiveMode 应用程序设置。

仅供参考:我更喜欢使用某种外观类,因此我不会处理代码中的魔术字符串,但为了简单起见,您将拥有类似的内容:

//CompressFilter class
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
  bool inLiveMode = bool.Parse(ConfigurationManager.AppSettings["InLiveMode"]);

  if(inLiveMode)
  {
    //Do the compression shiznit
  }
}
Run Code Online (Sandbox Code Playgroud)