无法使用ConfigurationManager.AppSettings读取Web.config

时间:2013-11-29 12:37:33

标签: c# .net visual-studio-2010 wcf configurationmanager

我已经构建了一个使用Web.config获取一些appSettings的WCF服务。在visual studio中它工作得很好,但是当我发布和安装服务时,它突然从App.config获取appSettings而不是从Web.config获取。

我知道这一点,因为我循环访问appSettings并使用以下代码将结果打印到控制台:

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

我的配置看起来像这样:

的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>
....

当我在视觉工作室跑步时,我得到:

enter image description here

但是当我在实时环境中使用已发布的代码时,我得到了这个:

enter image description here

为什么会发生这种情况?如何强制ConfigurationManager从Web.config而不是App.config获取appSettings。

2 个答案:

答案 0 :(得分:2)

如果你有一个标准的WCF项目,你应该只有Web.config文件,而不是App.config。

我会跳过使用appSettings的旧方式。请使用applicationSettings,方法是使用项目属性中的Settings-tab。

它将在Web.Config:

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

有关详细信息:appSettings vs applicationSettings. appSettings outdated?

答案 1 :(得分:1)

configurationManager用于从正在运行的项目的配置文件中选择值。例如,您已在Web服务器S1上公开了wcf,并且您正在从客户端计算机M1的控制台应用程序中使用它。现在,如果您的c#代码在S1上运行,那么它将从S1上的wcf代码文件夹中的web.config中选择值。但是,如果此代码在客户端计算机M1(使用该服务的控制台应用程序)上运行,那么它将从计算机M1中选择值。你所面对的,通常发生在发布之后。