繁体   English   中英

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

[英]Programmatically access the <compilation /> section of a web.config?

有什么方法可以访问web.config文件中的<compilation />标记?

我想检查文件中的“ debug ”属性是否设置为“ true ”,但似乎无法弄清楚该怎么做。 我尝试使用WebConfigurationManager ,但这似乎不允许我进入<compilation />部分。

更新:

我知道我可以轻松地像XML Document一样加载文件并使用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 ”),我只是不知道如何获取它。

采用:

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文档中进行查找。

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

毕竟,您始终可以将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;

尝试使用:

HttpContext.Current.IsDebuggingEnabled

您始终可以通过以下方式在编译器级别检查调试选项:

#if (DEBUG)

#endif

万一那是主意...

难道您只是将文件作为常规XML文件加载并使用XPath来获取节点?

尝试使用ConfigurationManager.GetSection方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM