Accessing appSettings from multiple Web.config fil

2019-02-17 13:29发布

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>

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>

Just to clarify in terms of relative paths, I now have two Web.config files, one at ./Web.config and one at ./Areas/PackageName/Web.config.

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?

2条回答
劳资没心,怎么记你
2楼-- · 2019-02-17 13:58

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;
查看更多
干净又极端
3楼-- · 2019-02-17 13:59

Try with

<appSettings file="<Path_To_Second_Web.Config>">
   ...
</appSettings >

in your project's Web.config

http://msdn.microsoft.com/en-us/library/aa903313(v=vs.71).aspx

查看更多
登录 后发表回答