Can't read Web.config with ConfigurationManager.AppSettings

11.1k views Asked by At

I have build a WCF service that uses Web.config to get some appSettings. In visual studio it works great but when I publish and instal the service it suddenly gets its appSettings from App.config and not from Web.config.

I know this because I loop through appSettings and printed the result to the console with this code:

foreach (string key in ConfigurationManager.AppSettings.AllKeys)
{
     Console.WriteLine("Name: {0} Value: {1}", key, ConfigurationManager.AppSettings[key]);
}

My configs look like this:

Web.config

  ....
  <appSettings>
    <add key="IQDir" value="C:\Program Files (x86)\Ridder iQ Client (lokaal)\Bin"/>
    <add key="FileURL" value="localhost:8080/WebPortal_2.0/"/>
  </appSettings>
  ....

App.config

....
  <appSettings>
    <add key="test1" value="wtf is going on!"/>
    <add key="test2" value="waargh"/>
    <add key="test3" value="I am getting a headache over here!!"/>
  </appSettings>
....

When I run in visual studio I get:

enter image description here

But when I use the published code inside live environment I get this:

enter image description here

Why is this happening and how can I force ConfigurationManager to get appSettings from Web.config instead of App.config.

2

There are 2 answers

1
cederlof On BEST ANSWER

If you have a standard WCF-project, you should only have the Web.config-file, not App.config.

I would skip the old way of using appSettings altogether. Use applicationSettings instead, by using the Settings-tab in the project's properties.

It will create this in Web.Config:

<applicationSettings>
    <Projectname.Properties.Settings>
        <setting name="Testenvironment" serializeAs="String">
            <value>True</value>
        </setting>
    </Projectname.Properties.Settings>
</applicationSettings>

For more information: appSettings vs applicationSettings. appSettings outdated?

1
Amer On

configurationManager is used to pick values from the configuration file of project under which it is running. For example, you have exposed your wcf on web server S1 and you are consuming it in a console app from client machine M1. Now if your c# code is running on S1 then it will pick values from web.config from wcf code folder on S1. But if this code is running on client machine M1 (the console app consuming the service), then it will pick values from machine M1. What you are facing, normally happened after publish.