How can I identify whether an ASP.NET site is bein

2020-08-01 06:44发布

How can I determine what 'mode' my site is running under?

In this specific case, I have code in the code-behind pages that should act one way in 'release' mode - that is someone navigating there with a browser, and another way if I'm in debug mode coming from VS2008. (These are things like identifying which SQL connect string to use, whether or not to display certain error or warning messages, etc)

VS2008 is configured to go through IIS for a variety of reasons (Cassini is not an option).

Searching all through the help I can't find anything but there HAS to be a way to identify how the website was started.

Thanks in advance.

4条回答
萌系小妹纸
2楼-- · 2020-08-01 07:20
HttpContext.Current.IsDebuggingEnabled

See this article

查看更多
Lonely孤独者°
3楼-- · 2020-08-01 07:20

I would use the

#if DEBUG
    // ...
#else
    // ...
#endif

approach, however, I'd only use this for Exception catching in the "Main" method:

  • If debug, then don't catch (so the debugger can catch any uncaught exceptions),
  • if release, then show an error page.

These don't change the flow of the program, just don't do that, there be dragons :)

If you look at connection strings, for example, I'd just put them in web.config.

查看更多
Luminary・发光体
4楼-- · 2020-08-01 07:43

I use this method to detect whether debug is on in the compilation section:-

bool DebugModeOn()
{
    System.Web.Configuration.CompilationSection configSection =
             (System.Web.Configuration.CompilationSection)HttpContext.Current.GetSection("system.web/compilation");
    return configSection.Debug;

}

This isn't perfect for exactly what you are asking. However since this should be false in production and true in development it may be good enough.

Edit: Or you could simply use the context's IsDebuggingEnabled property as Olivier PAYEN points out. :P oops.

查看更多
ら.Afraid
5楼-- · 2020-08-01 07:45

I'm not sure what you mean. If you want to know if the application is currently being debugged, you can check the System.Diagnostics.Debugger.IsAttached property. If you want to know if the application is compiled in debug mode, then you can do this:

#if DEBUG
   const bool DebugMode = true;
#else
   const bool DebugMode = false;
#endif

Also, you can use ConditionalAttribute:

[System.Diagnostics.Conditional("DEBUG")]
public void ThisMethodWillOnlyExecuteInDebugMode()
{
}

I strongly suggest reconsidering that though - in my experience, having different release and debug behaviour is an excellent way to introduce bugs to your production code.

查看更多
登录 后发表回答