如何从代码 "inside" 服务访问 IIS 中托管的 WCF 服务的 web.config

How to access the web.config for a WCF service hosted in IIS from the code "inside" the service

正如标题所说,在重新定义我们的目标后,我们将 2 个服务缩减为 1 个,该服务托管在 Windows 2019 服务器上的 IIS 10.0 中,使用 BasicHttpBinding - 我通过反复试验发现主要问题我之前的问题是由于所述服务器不属于本地 DNS 服务的一部分。所以我 re-wrote 使用纯 IP 连接到我们的数据库服务器的连接字符串。这行得通。为了使配置更容易,我在我的服务 web.config

中的 appSettings 部分添加了新行
<appSettings>
<add key="Database" value="<whole connection string>"/>

我找到了 Microsoft 提供的 code-snippet 来访问 web.config - 但它似乎解析错误 web.config 因为我的数据丢失/解析时整个部分似乎是空的...

我用过的代码

        //Scan Thru the keys and use the Configuration Manager to make this happen
        System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(null) as System.Configuration.Configuration;
        // Get the appSettings.
        KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
        String ret="";
        foreach (string key in appSettings.AllKeys)
        {
            //Get your key
            string tmpKey = appSettings[key].Value;

            switch (key)
            {
                case "Database":
                    ret = tmpKey;
                    break;
            }
        }

然后我会使用 "ret" 建立实际的连接...但到目前为止失败了,因为上面的代码在 appSettings.AllKeys 中找不到 "anything"(collection 是空的) 对工作代码的任何提示将不胜感激。或者 null 是错误的参数,尽管代码提示表明 null 指向原始 web.config

您应该可以使用

访问应用设置
ConfigurationManager.AppSettings["Database"]

通常情况下,您可以使用以下代码片段来获取 AppSettings 部分中的值。

var result = ConfigurationManager.AppSettings["mykey"];
            Console.WriteLine(result.ToString());

这里有官方的例子和解释
https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.appsettings?view=netframework-4.8
https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager?view=netframework-4.8
如果有什么我可以帮忙的,请随时告诉我。