C# 在运行时检查asp.net Web应用程序是否处于调试模式的首选方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16357490/
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-10 00:50:04  来源:igfitidea点击:

A preferred way to check if asp.net web application is in debug mode during runtime?

c#asp.netweb-config

提问by Nenotlep

During compile time I can do a check like

在编译期间我可以做一个检查

#if DEBUG
    Log("something");
#endif

But what would be the preferred to check if debug="false"is set in Web.config during runtime?

但是debug="false"在运行时检查是否在 Web.config 中设置的首选是什么?

回答by Vasiliy

In some cases, you may need HttpContext.Current.IsDebuggingEnabled(sort of obvious, but nonetheless)

在某些情况下,您可能需要HttpContext.Current.IsDebuggingEnabled(有点明显,但仍然如此)

回答by StuartLC

There's another, non-programmatic external and empirical way to check if you've accidentally left the debug=trueattribute on system.web/compilationon a Asp.Net website, i.e. to detect if you've left this configuration on in web.config:

还有另一种非编程的外部和经验方法来检查您是否不小心在 Asp.Net 网站上保留了该debug=true属性system.web/compilation,即检测您是否在 web.config 中保留了此配置:

 <system.web>
    <compilation debug="true" targetFramework="xxx"/>

By using a tool such as Fiddler, you can intercept a GET request to your web site, and then change this so that to issue a non-Standard DEBUGHTTP Verb to the site, along with an extra Command: stop-debugHeader.

通过使用诸如Fiddler 之类的工具,您可以拦截对您网站的 GET 请求,然后对其进行更改,以便向该网站发出一个非标准DEBUGHTTP 动词以及一个额外的Command: stop-debug标头。

  • Select a GET request to your site and drag it into the Composer
  • Switch to the Rawtab (since DEBUG isn't a standard HTTP verb option)
  • Edit the Verb from GETto DEBUG
  • Add an extra Command: stop-debugHeader (above the Cookies), but leave the rest of the Headers and Cookies in place
  • Execute the DEBUGcommand
  • 选择对您站点的 GET 请求并将其拖到 Composer 中
  • 切换到Raw选项卡(因为 DEBUG 不是标准的 HTTP 动词选项)
  • 编辑动词从GETDEBUG
  • 添加一个额外的Command: stop-debug标题(在 Cookie 上方),但保留其余的标题和 Cookie
  • 执行DEBUG命令

If the Web site returns 200 and the content OK, then you know you've left debug on. The web site will return 403 - Forbiddenif debugis off.

如果 Web 站点返回 200 和 content OK,那么您就知道您已经将调试留在了。403 - Forbidden如果debug关闭,该网站将返回。

Fiddler Screenshot

提琴手截图

If you've got your website building on a CI/CD build pipeline, best way to turn debug off is to add the following XDT in your Web.Release.config

如果您的网站是在 CI/CD 构建管道上构建的,那么关闭调试的最佳方法是将以下XDT添加到您的Web.Release.config

<system.web>
  <compilation xdt:Transform="RemoveAttributes(debug)" />
</system.web>

(Turning debug off in Production is a common security audit requirement)

(在生产中关闭调试是一个常见的安全审计要求)