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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1734741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:23:45  来源:igfitidea点击:

How to execute code only in debug mode in ASP.NET

c#asp.netdebugging

提问by Omu

I have an ASP.NET web application and I have some code that I want to execute only in the debug version. How to do this?

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

采纳答案by empi

#if DEBUG
your code
#endif

You could also add ConditionalAttributeto method that is to be executed only when you build it in debug mode:

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

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

回答by Shimmy Weitzhandler

I declared a property in my base page, or you can declare it in any static class you have in applicaition:

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

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

Then to achieve your desire do:

然后为了实现你的愿望:

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

回答by dtb

Detecting ASP.NET Debug mode

检测 ASP.NET 调试模式

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

From MSDN:

MSDN

HttpContext.IsDebuggingEnabled Property

Gets a value indicating whether the current HTTP request is in debug mode.

HttpContext.IsDebuggingEnabled 属性

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