以编程方式访问web.config的部分?
有没有办法访问web.config文件中的标签?
我想检查文件中的“ debug ”属性是否设置为“ true ”,但我似乎无法弄清楚如何做到这一点。 我已经尝试过使用WebConfigurationManager
,但这似乎不允许我进入部分。
更新:
我知道我可以轻松地像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
‘),我只是想不通如何得到它。
使用:
using System.Configuration; using System.Web.Configuration;
…
CompilationSection configSection = (CompilationSection) ConfigurationManager.GetSection( "system.web/compilation" );
然后,您可以检查configSection.Debug
属性。
提示:如果您需要知道如何从配置文件中获取值,请检查\Windows\Microsoft.net\Framework\
文件夹中的machine.config文件。 在那里,您可以看到如何定义所有配置节处理程序。 一旦知道了配置处理程序的名称(在本例中为CompilationSection),就可以在.Net文档中查找它。
检查您是否在调试模式下运行的简单方法是使用HttpContext.IsDebuggingEnabled属性。 它从编译元素的调试属性中得到答案,这与您尝试执行的操作相同。
毕竟,您始终可以将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;
您始终可以通过将代码包含在编译器级别来检查调试选项
#if (DEBUG) #endif
如果是这个想法……
尝试使用:
HttpContext.Current.IsDebuggingEnabled
你不能只是将文件作为常规XML文件加载并使用XPath来获取节点吗?
尝试使用ConfigurationManager.GetSection方法。