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

12
有没有办法访问 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

以上所有方法都返回null。我假设有一种方法可以访问此配置部分,因为已经存在一个类('CompilationSection'),但我无法弄清楚如何获取它。


你是否将你的部分添加到configSections中?像这样: <configSections> <section name="compilation" type="xxx" /> ... </configSections> - cameron
7个回答

27

使用:

using System.Configuration;
using System.Web.Configuration;

...

  CompilationSection configSection =
          (CompilationSection) ConfigurationManager.GetSection( "system.web/compilation" );

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

24

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


这是最佳答案,当您拥有一个 HttpContext 实例时(即在控制器中处理请求时),但如果您需要在应用程序的另一个地方执行此操作,例如 Global.asax 代码,则需要使用 @MikeScott 的答案。 - Jacob Stamm

3
毕竟,您总是可以将Web.config文件加载到XmlDocument中,并使用XPath查询来查找!
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/Web.config"));     
doc.SelectSingleNode("/configuration/system.web/compilation/@debug");

然而,我建议您使用Configuration.GetSection方法来解决问题。

CompilationSection section = 
    Configuration.GetSection("system.web/compilation") as CompilationSection;
bool debug = section != null && section.Debug;

2
您可以通过将代码包含在中以检查编译器级别上的调试选项。
#if (DEBUG)

#endif

如果这是你的想法...


这不是web.config标志,因为它可以在运行时更改。正如你所写的,这仅限于编译时,并且取决于是否进行DEBUG或RELEASE构建(编译)。这不是这里所要求的。 - Marc

1
尝试使用:

HttpContext.Current.IsDebuggingEnabled

0

你不能只将文件作为常规的XML文件加载并使用XPath获取节点吗?


0
尝试使用 ConfigurationManager.GetSection 方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接