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

Omu*_*Omu 35 c# asp.net debugging

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

emp*_*mpi 73

#if DEBUG
your code
#endif
Run Code Online (Sandbox Code Playgroud)

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

[Conditional("DEBUG")]
void SomeMethod()
{
}
Run Code Online (Sandbox Code Playgroud)


dtb*_*dtb 63

检测ASP.NET调试模式

if (HttpContext.Current.IsDebuggingEnabled)
{
    // this is executed only in the debug version
}
Run Code Online (Sandbox Code Playgroud)

来自MSDN:

HttpContext.IsDebuggingEnabled属性

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


Shi*_*mmy 11

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

    public static bool IsDebug
    {
        get
        {
            bool debug = false;
#if DEBUG
            debug = true;
#endif
            return debug;
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后实现你的愿望:

    if (IsDebug)
    {
        //Your code
    }
    else 
    {
        //not debug mode
    }
Run Code Online (Sandbox Code Playgroud)

  • 默认情况下debug会被初始化为false,所以你IsDebug方法总会返回false,你错过了bool debug = true吗? (2认同)