如何从服务“内部”的代码访问托管在 IIS 中的 WCF 服务的 web.config

Posted

技术标签:

【中文标题】如何从服务“内部”的代码访问托管在 IIS 中的 WCF 服务的 web.config【英文标题】:How to access the web.config for a WCF service hosted in IIS from the code "inside" the service 【发布时间】:2020-07-27 06:16:39 【问题描述】:

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

<appSettings>
<add key="Database" value="<whole connection string>"/>

我找到了 Microsoft 提供的用于访问 web.config 的 code-sn-p - 但它似乎解析了错误的 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 中找不到“任何东西”(集合为空),因此失败了 任何有关工作代码的提示将不胜感激。或者是 null 是错误的参数,尽管代码提示表明 null 指向原始 web.config

【问题讨论】:

你试过ConfigurationManager.AppSettings["Database"]吗?配置代码可能是邪恶的,因为它不会抛出异常并说“不,我找不到你要找的东西”,它通常会返回一个缺少部分或值为 null 的 Configuration 对象。有一个 Configuration.HasFile 属性。如果为真,则您的值来自文件。如果是假的,它们来自……我不知道。没有文件。如果您检查config.HasFile,它可能是错误的。 再google-fu是的......解决方案很简单 【参考方案1】:

通常,您可以使用以下代码 sn-ps 获取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.8https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager?view=netframework-4.8 如果有什么可以帮助的,请随时告诉我。

【讨论】:

【参考方案2】:

您应该能够使用

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

【讨论】:

以上是关于如何从服务“内部”的代码访问托管在 IIS 中的 WCF 服务的 web.config的主要内容,如果未能解决你的问题,请参考以下文章