【问题标题】:How can I check whether I am in a debug or release build in a web app?如何检查我是否处于 Web 应用程序的调试或发布版本中?
【发布时间】:2008-11-03 12:24:39
【问题描述】:

在任何(非 Web).net 项目中,编译器会自动声明 DEBUG 和 TRACE 常量,因此我可以使用条件编译来例如在调试和发布模式下以不同方式处理异常。

例如:

#if DEBUG
    /* re-throw the exception... */
#else
    /* write something in the event log... */
#endif

如何在 ASP.net 项目中获得相同的行为? 看起来 web.config 中的 system.web/compilation 部分可能是我需要的,但是如何以编程方式检查它? 还是我最好自己声明一个 DEBUG 常量并在发布版本中将其注释掉?

编辑:我在 VS 2008

【问题讨论】:

  • 澄清一下:IDE(至少是我的版本?)无法在 web 项目上声明 DEBUG 和 TRACE 常量!

标签: c# asp.net debugging


【解决方案1】:

要在 Andrews 答案之上添加,您也可以将其包装在一个方法中

public bool IsDebugMode
{
  get
  {
#if DEBUG 
    return true;
#else
    return false;
#endif
  }
}

【讨论】:

    【解决方案2】:

    看看ConfigurationManager.GetSection() - 这应该让你大部分时间都在那里.. 但是,我认为你最好在调试和发布模式之间切换并让编译器确定执行包含的“#if DEBUG”声明。

    #if DEBUG
    /* re-throw the exception... */
    #else
    /* write something in the event log... */
    #endif
    

    以上内容可以正常工作,只需确保您至少有两个构建配置(右键单击您正在处理的项目并转到“属性”,其中有一个关于构建的部分) - 确保一个这些构建中的“定义调试”已选中,而另一个则没有。

    【讨论】:

    • 谢谢,ConfigurationManager.GetSection() 正是我想要的!
    【解决方案3】:

    这就是我最终做的:

    protected bool IsDebugMode
    {
        get
        {
            System.Web.Configuration.CompilationSection tSection;
            tSection = ConfigurationManager.GetSection("system.web/compilation") as System.Web.Configuration.CompilationSection;
            if (null != tSection)
            {
                return tSection.Debug;
            }
            /* Default to release behavior */
            return false;
        }
    }
    

    【讨论】:

      【解决方案4】:

      我个人不喜欢“#if debug”改变布局的方式。我通过创建一个仅在调试模式下调用并通过引用传递布尔值的条件方法来做到这一点。

      [Conditional("DEBUG")]
      private void IsDebugCheck(ref bool isDebug)
      {
          isDebug = true;
      }
      
      public void SomeCallingMethod()
      { 
          bool isDebug = false;
          IsDebugCheck(ref isDebug);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-02
        • 2012-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多