以编程方式访问web.config的<compilation />部分?

Dan*_*ert 10 .net c# asp.net configuration

有没有办法访问<compilation />web.config文件中的标记?

我想检查文件中的" debug "属性是否设置为" true ",但我似乎无法弄清楚如何做到这一点.我已经尝试过使用了WebConfigurationManager,但这似乎不允许我进入该<compilation />部分.

更新:

我知道我可以轻松地像XML文档一样加载文件并使用XPath,但我希望框架中已经存在一些可以为我做这件事的东西.似乎会有一些东西,因为已经有方法来获取应用程序设置和连接字符串.

我也尝试过WebConfigurationManager.GetSection()以下几种方法:

WebConfigurationManager.GetSection("compilation")// Name of the tag in the file
WebConfigurationManager.GetSection("CompilationSection") // Name of the class that I'd expect would be returned by this method
WebConfigurationManager.GetSection("system.web") // Parent tag of the 'compilation' tag
Run Code Online (Sandbox Code Playgroud)

所有上述方法都返回null.我假设有一种方法可以进入这个配置部分,因为有一个类已经存在(' CompilationSection'),我只是想不通如何得到它.

Mik*_*ott 25

使用:

using System.Configuration;
using System.Web.Configuration;
Run Code Online (Sandbox Code Playgroud)

...

  CompilationSection configSection =
          (CompilationSection) ConfigurationManager.GetSection( "system.web/compilation" );
Run Code Online (Sandbox Code Playgroud)

然后,您可以查看configSection.Debug酒店.

提示:如果您需要知道如何从配置文件中获取值,请检查文件\Windows\Microsoft.net\Framework\<version>\CONFIG夹中的machine.config文件.在那里,您可以看到如何定义所有配置节处理程序.一旦知道配置处理程序的名称(在本例中为CompilationSection),就可以在.Net文档中查找它.


小智 23

检查您是否在调试模式下运行的简单方法是使用HttpContext.IsDebuggingEnabled属性.它从编译元素的调试属性中获得答案,这与您尝试执行的操作相同.