从多个Web.config文件中访问的appSettings [英] Accessing appSettings from multiple Web.config files

查看:140
本文介绍了从多个Web.config文件中访问的appSettings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设计一个ASP.NET MVC4 Web应用程序项目。在我的项目的根,我已经习惯默认的的Web.config 我的相应元素文件。特别是,我已经定义了几个的appSettings 元素。作为一个例子摘录证明这一点:

I am designing an ASP.NET MVC4 Web App project. In the root of my project, I have the customary default Web.config file with my corresponding elements. In particular, I have a few appSettings elements defined. As an example excerpt to demonstrate this:

<appSettings>
    <add key="foo" value="bar" />
</appSettings>

当然,我可以code内使用 ConfigurationManager.AppSettings访问此元素[富] 。这完全适用于我。不过,我创建的NuGet包旁边我的项目。该软件包是自己的目录内安装在我的项目的领域目录。在这里,我的包的根,我还有一个的Web.config 文件。这是这样,当另一个用户导入的NuGet包,该包的资源的配置是天然的包。让包的的Web.config 包含以下内容:

Naturally, I can access this element within code using ConfigurationManager.AppSettings["foo"]. This works perfectly for me. However, I am creating a NuGet package alongside my project. The package is installed within its own directory under my project's Areas directory. Here, in my package's root, I have another Web.config file. This is so that, when another user imports the NuGet package, the configuration for the package resources is native to the package. Let the package's Web.config contain the following:

<appSettings>
    <add key="dirEnabled" value="true" />
</appSettings>

只是为了在相对路径方面澄清,我现在有两个Web.config文件中,一个在 ./的Web.config ,一个在 ./Areas/PackageName/Web.config

在我的包,我想检索 dirEnabled 的值。要做到这一点,我拨打电话: ConfigurationManager.AppSettings [dirEnabled] 。但是,这将引发一个错误。它看起来好像只的appSettings集合正在从检索./的Web.config ,而不是我的包的配置文件。 是它在所有可能抓住从我的包的配置文件,而不是项目的根配置文件中的appSettings集合?

Within my package, I want to retrieve the value for dirEnabled. To do so, I make the call: ConfigurationManager.AppSettings["dirEnabled"]. However, this throws an error. It appears as if only the collection of appSettings is being retrieved from ./Web.config and not my package config file. Is it at all possible to grab the appSettings collection from my package's config file rather than the project root config file?

推荐答案

想通了!要使用不同的配置文件,包括 WebConfigurationmanager 。因此,要访问的的appSettings ./地区/ PACKAGENAME / Web.config中,只需使用:

Figured it out! To use a different config file, incorporate WebConfigurationmanager. So, to access the appSettings of ./Areas/PackageName/Web.config, simply use:

var config = WebConfigurationManager.OpenWebConfiguration("~/Areas/PackageName");
string dirE = config.AppSettings.Settings["dirEnabled"].Value;

这篇关于从多个Web.config文件中访问的appSettings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆