Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigurationManager reading wrong file - Web.config instead of App.config

I was working on ASP.NET MVC project and decided to extract some functionality to a separate class library project (in the same solution).

I moved some of the elements in <appSettings></appSettings> from Web.config in main project (let's call it project A) to App.config in class library project (let's call it project B). I added a reference to System.Configuration.dll to access the ConfigurationManager in project B.

Sample App.config file is for project B is below.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Key1" value="Value1"/>
    <add key="Key2" value="Value2"/>
  </appSettings>
</configuration>

I access these settings as follows (in project B).

string key1 = ConfigurationManager.AppSettings["Key1"];
string key2 = ConfigurationManager.AppSettings["Key2"];

I noticed that the values for key1 and key2 returned by ConfigurationManager are null.

When debugging I see that ConfigurationManager pull values from the original Web.config in project A (the other entires in <appsettings></appsettings> section that I did not move to project B)!

This does not make any sense to me. Could someone tell me what I am doing wrong, so I could access settings in App.config?

Thanks.

like image 584
nomad Avatar asked Sep 09 '13 17:09

nomad


People also ask

Is app config the same as web config?

The web. config file is required for ASP.NET webpages. The app. config file is optional in an application and doesn't have to be used when writing desktop applications.

Does Web config override machine config?

The machine. config file file is at the highest level in the configuration hierarchy while Web. config file is to override the settings from the machine. config file.

How do I override ConfigurationManager appSettings?

It appears there is a way to do this in . NET 3.5 by setting the allowOverride attribute in the appSettings definition section of machine. config. This allows you to override the entire section in your own app.


1 Answers

App.config that resides in a Class Library project would not be loaded (at least not without extra effort), the only configuration loaded by the framework is the Client configuration (i.e the Web.config of a project that references and uses your Class Library).

See this answer for possible solutions.

like image 102
haim770 Avatar answered Nov 04 '22 11:11

haim770