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?
Yes you can have two web. config files in application. There are situations where your application is divided in to modules and for every module you need separate configuration. For example if you have a application which has two modules lets say accounts and sales.
Locate the web. config file in the root directory of your application (or create one if it does not already exist). Add an <appSettings> element. Add <add> child elements along with key / value pairs to the <appSettings> element as required.
Why appsettings keys (in web. config) are not case sensitive ? The default comparer is a CaseInsensitiveComparer that uses the conventions of the invariant culture; that is, key comparisons are case-insensitive by default.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With