使用ConfigurationManager.RefreshSection重新加载配置而无需重新启动应用程序

Kie*_*ton 39 c# asp.net performance settings

有没有人在网络应用程序中工作?

无论我做什么,似乎我的appSettings部分(使用appSettings file =".\ Site\site.config"从web.config重定向)都没有重新加载.

我注定要重新启动应用程序吗?我希望这种方法能够让我找到更高效的解决方案.

更新:

通过'重新加载',我的意思是刷新ConfigurationManager.AppSettings,而不必完全重启我的ASP.NET应用程序,并且不得不承担通常的启动延迟.

G-W*_*Wiz 48

确保将正确的区分大小写的值传递给RefreshSection,即

ConfigurationManager.RefreshSection("appSettings");
Run Code Online (Sandbox Code Playgroud)

  • 你怎么会刷新整个文件? (4认同)
  • 请注意,更改app.config不会影响正在调试的程序.如果要在调试期间刷新值,则应更改<runningApplicationName> .vshost.exe.config以查看更改.但是,它就像您自己运行应用程序时所描述的那样工作. (3认同)

小智 14

当您为appSettings使用外部配置文件时,这似乎是一个缺陷(可能是一个错误).我已尝试使用configSource属性,而RefreshSection根本无法工作,我假设使用文件属性时这是相同的.如果你将appSettings移回web.config中,RefreshSection将完美运行,否则我担心你注定失败了.

  • 我也注意到了这一点.有解决方案吗 (4认同)

Wil*_*ich 5

由于某种原因ConfigurationManager.RefreshSection("appSettings")对我不起作用。将 Web.Config 重新加载到 Configuration 对象中似乎可以正常工作。以下代码假定 Web.Config 文件是执行 (bin) 文件夹下的一个目录。

ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
Uri uriAssemblyFolder = new Uri(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));
string appPath = uriAssemblyFolder.LocalPath;
configMap.ExeConfigFilename = appPath + @"\..\" + "Web.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None); 
Run Code Online (Sandbox Code Playgroud)

并使用如下:

string webConfigVariable = config.AppSettings.Settings["webConfigVariable"].Value;
Run Code Online (Sandbox Code Playgroud)