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

3

我建立了一个使用Web.config获取一些appSettings的WCF服务。在Visual Studio中,它运行得很好,但是当我发布和安装服务后,它突然从App.config而不是Web.config获取其appSettings。

我知道这是因为我使用以下代码循环遍历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>
....

当我在Visual Studio中运行时,会出现以下情况: enter image description here 但是当我在实际环境中使用已发布的代码时,会出现以下情况: enter image description here 为什么会出现这种情况,如何强制ConfigurationManager从Web.config获取appSettings而不是App.config?

为什么你需要同时拥有 web.config 和 app.config? - stuartd
1
您尝试使用System.Web.Configuration.WebConfigurationManager了吗? - Tobberoth
@Tobberoth 我已经尝试了很多东西,包括 WebConfigurationManager。结果都一样。 - botenvouwer
1
@sirwilliam 首先,你为什么要有一个 app.config 文件?其次,你确定你正在正确地进行测试吗?根据我在 MSDN 文档中所看到的,WebConfigurationManager 无法打开 app.config 文件,它只能打开 Web 应用程序和机器配置文件。 - Tobberoth
@Tobberoth 这就是为什么我问这个问题,我不明白为什么会发生这种情况。在测试环境中,它做了应该做的事情,但当我发布后,它开始表现奇怪。 - botenvouwer
2个回答

2

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

我建议完全跳过使用appSettings的旧方法。相反,使用项目属性中的Settings选项卡来使用applicationSettings。

这将在Web.Config中创建以下内容:

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

更多信息请参考:appSettings与applicationSettings,appSettings已过时?


我也有一个App.config文件。它是自动创建的。 - botenvouwer

2

configurationManager被用于从它所运行的项目的配置文件中获取值。例如,您已经在Web服务器S1上公开了WCF并且您正在从客户端机器M1的控制台应用程序中使用它。现在,如果您的C#代码正在S1上运行,则它将从S1上的wcf代码文件夹中的web.config中获取值。但是,如果此代码在客户端机器M1上运行(消费服务的控制台应用程序),则它将从M1机器上获取值。通常情况下,这是发布后遇到的问题。


2
我现在正在本地机器上运行它进行测试,但到目前为止,在我测试过的任何机器上都无法正常工作。奇怪的是,WebConfigurationManager从App.config获取其appSettings。有没有办法查看WebConfigurationManager获取其.config文件的路径? - botenvouwer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接