我可以在 运行 时而不是在编译时从 app.config 获取设置吗?

Can I get settings from app.config at run time rather than when compiled?

我有许多项目需要访问设置、数据库连接、网络 api url、身份验证服务器 url 等,这些将根据其部署而改变。

应用程序可以多次部署到不同的部门,每个部门都有不同的数据库和网络服务器。

最初我使用 appSettings 并将它们公开为属性。这似乎在 ide(Visual Studio 2013)的开发中起作用。

我遵循了建议 here 以正确获取位置并且它似乎有效。 所以最初我有:

  private static KeyValueConfigurationCollection GetAppSettings()
    {
        // The dllPath can't just use Assembly.GetExecutingAssembly().Location as ASP.NET doesn't copy the config to shadow copy path
        var dllPath = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath;
        var dllConfig = ConfigurationManager.OpenExeConfiguration(dllPath);

        // Get the appSettings section
        var appSettings = (AppSettingsSection)dllConfig.GetSection("appSettings");
        return appSettings.Settings;
    }

 public string AknowledgeSTSOrigin
        {
            get
            {
                string setting;
                if (_aknowledgeSTSOrigin != null)
                {
                    setting = _aknowledgeSTSOrigin;
                }
                else
                {
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        setting = "https://localhost:44333";
                    }
                    else
                    {
                        var settings = GetAppSettings();
                        if (settings.Count > 0)
                        {
                            setting = settings["AknowledgeSTSOrigin"].Value;
                        }
                        else
                        {
                            setting = System.Configuration.ConfigurationManager.AppSettings["AknowledgeSTSOrigin"];
                        }
                    }
                     _aknowledgeSTSOrigin =setting;
                }
                return setting;
            }
        }

在某些时候它停止工作了 - 但不幸的是我没有 idea 何时或为什么因为我在 ide 中 运行 所以它总是默认为调试器附条件。 此时的问题是上述所有路由都从 appSettings 返回 null。 查找问题时,发现现在推荐使用project properties。我这样做了 - app.config 中出现了一个新的 ApplicationSettings 部分,并且找到了属性。 所以上面简化为:

setting = Properties.Settings.Default.AknowledgeSTSOrigin;

效果很好,我将值设置为 localhost 以在 ide 中测试 运行 - 一切正常。我编译并发布了应用程序,然后尝试在服务器上更改 app.config。它仍然无法在服务器上运行。但是如果我在我的机器上更改 app.config 以具有服务器设置,重建并发布它,它就可以工作了。

所以看起来这个方法在编译时从app.config获取属性。

我想做的是能够在运行时从配置文件中获取它们。因此,一次构建应用程序,多次部署,然后仅使用特定于部署的设置更新配置。

我试过用谷歌搜索并检查 SO,但没有找到任何有用的东西。

尝试添加

 Properties.Settings.Default.Reload();

根据 this post 但不工作。

目标框架 = .Net 4.5 及其 class 库。错误消息显示它仍然在编译时从配置文件中获取值。 (错误消息不相关,因为如果它有正确的路径就不会有错误)

编辑: 现在变得更加困惑了。发现以下 post,其中提到默认是要编译的属性,除非您将 GenerateDefaultValueInCode 设置为 false。我已经这样做了,现在又回到了相同的结果,因为它为属性返回 null。出于某种原因,尽管将所有属性的值设置为 false,它们仍然可见嵌入在 dll 中。

找到了! 问题发生在 class 库中。 虽然我在 class 库中创建了设置并且这些设置被添加到 app.config,但它实际上并没有在那里找回它们。相反,它是使用 class 库的父级的 web.config。 我将设置放在 web.config 中,它似乎有效。