如何仅在ASP.NET中的调试模式下执行代码

时间:2009-11-14 16:32:09

标签: c# asp.net debugging

我有一个ASP.NET Web应用程序,我有一些代码,我只想在调试版本中执行。怎么做?

3 个答案:

答案 0 :(得分:73)

#if DEBUG
your code
#endif

您还可以将ConditionalAttribute添加到仅在以调试模式构建时才执行的方法:

[Conditional("DEBUG")]
void SomeMethod()
{
}

答案 1 :(得分:63)

Detecting ASP.NET Debug mode

if (HttpContext.Current.IsDebuggingEnabled)
{
    // this is executed only in the debug version
}

来自MSDN

  

HttpContext.IsDebuggingEnabled属性

     

获取一个值,该值指示当前HTTP请求是否处于调试模式。

答案 2 :(得分:11)

我在我的基页中声明了一个属性,或者你可以在应用程序中的任何静态类中声明它:

    public static bool IsDebug
    {
        get
        {
            bool debug = false;
#if DEBUG
            debug = true;
#endif
            return debug;
        }
    }

然后实现你的愿望:

    if (IsDebug)
    {
        //Your code
    }
    else 
    {
        //not debug mode
    }