C# 使用 ConfigurationManager.RefreshSection 在不重新启动应用程序的情况下重新加载配置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/179254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reloading configuration without restarting application using ConfigurationManager.RefreshSection
提问by Kieran Benton
Has anyone got this working in a web application?
有没有人在 Web 应用程序中使用过这个?
No matter what I do it seems that my appSettings section (redirected from web.config using appSettings file=".\Site\site.config") does not get reloaded.
无论我做什么,似乎我的 appSettings 部分(使用 appSettings file=".\Site\site.config" 从 web.config 重定向)都没有重新加载。
Am I doomed to the case of having to just restart the application? I was hoping this method would lead me to a more performant solution.
我是否注定要重新启动应用程序?我希望这种方法能让我找到一个更高效的解决方案。
Update:
更新:
By 'reloading' I mean refreshing ConfigurationManager.AppSettings without having to completely restart my ASP.NET application and having to incur the usual startup latency.
“重新加载”是指刷新 ConfigurationManager.AppSettings 而不必完全重新启动我的 ASP.NET 应用程序,也不必招致通常的启动延迟。
采纳答案by G-Wiz
Make sure you are passing the correct case sensitivevalue to RefreshSection, i.e.
确保您将正确的区分大小写的值传递给 RefreshSection,即
ConfigurationManager.RefreshSection("appSettings");
回答by Seibar
The App.Config settings are cached in memory when the application starts. For this reason, I don't think you'll be able to change those settings without restarting your application. One alternative that should be pretty straight forward would be to create a separate, simple XML configuration file, and handle loading/caching/reloading it yourself.
App.Config 设置在应用程序启动时缓存在内存中。出于这个原因,我认为您将无法在不重新启动应用程序的情况下更改这些设置。一种非常直接的替代方法是创建一个单独的、简单的 XML 配置文件,并自己处理加载/缓存/重新加载。
回答by Seibar
This seems to be a flaw (maybe a bug) when using an external config file for your appSettings. I've tried it using the configSource attribute and RefreshSection simply never works, I'm assuming this is the same when using the file attribute. If you move your appSettings back inside your web.config RefreshSection will work perfectly but otherwise I'm afraid you're doomed.
在为您的 appSettings 使用外部配置文件时,这似乎是一个缺陷(可能是一个错误)。我已经使用 configSource 属性尝试过它,而 RefreshSection 根本不起作用,我假设使用文件属性时这是相同的。如果你将你的 appSettings 移回你的 web.config RefreshSection 将完美地工作,但否则我担心你注定要失败。
回答by Seibar
To write, call it this way:
要写,这样称呼它:
Dim config As System.Configuration.Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
Dim config As System.Configuration.Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
Return AddOrUpdateAppSetting(config, "YourSettingKey", "YourValueForTheKey")
返回 AddOrUpdateAppSetting(config, "YourSettingKey", "YourValueForTheKey")
To read and be sure you get the values in file, instead of those in cache, read it this way:
要读取并确保获取文件中的值,而不是缓存中的值,请按以下方式读取:
Dim config As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration("~")
Return config.AppSettings.Settings("TheKeyYouWantTheValue").Value
Full example:
完整示例:
Protected Shared Function AddOrUpdateAppSetting( _
ByVal Config As System.Configuration.Configuration _
, ByVal TheKey As String _
, ByVal TheValue As String _
) As Boolean</p>
Dim retval As Boolean = True
Dim Itm As System.Configuration.KeyValueConfigurationElement = _
Config.AppSettings.Settings.Item(TheKey)
If Itm Is Nothing Then
If Config.AppSettings.Settings.IsReadOnly Then
retval = False
Else
Config.AppSettings.Settings.Add(TheKey, TheValue)
End If
Else
' config.AppSettings.Settings(thekey).Value = thevalue
If Itm.IsReadOnly Then
retval = False
Else
Itm.Value = TheValue
End If
End If
If retval Then
Try
Config.Save(ConfigurationSaveMode.Modified)
Catch ex As Exception
retval = False
End Try
End If
Return retval
End Function
回答by Vince
Have you tried storing your AppSettings in its own external file?
您是否尝试将您的 AppSettings 存储在其自己的外部文件中?
From app.config/web.config:
从 app.config/web.config:
<appSettings configSource="appSettings.config"></appSettings>
appSettings.config:
appSettings.config:
<?xml version="1.0"?>
<appSettings>
<add key="SomeKey" value="SomeValue" />
</appSettings>
Changes made to appSettings.config should be reflected instantly. More info: http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx
对 appSettings.config 所做的更改应立即反映出来。更多信息:http: //msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx
回答by yamspog
Yes. you are stuck with iis restarting.
是的。你被 iis 重启困住了。
There is a feature with asp.net 4.0 and iis 7.5 where the initial startup is removed.
asp.net 4.0 和 iis 7.5 有一项功能,其中删除了初始启动。
回答by badpanda
I am not sure if this is possible in a web app, but it works in a desktop app. Try using ConfigurationSettings rather than ConfigurationManager (it will yell at you for using outdated classes...), then reading all the data into a class. When you wish to refresh, simply create a new instance and drop all references to the old instance. My theory for why this works (might be wrong): when you don't directly access the app.config file the entire time you are running, the file lock is dropped by the application. Then, edits can be made when you are not accessing the file.
我不确定这在网络应用程序中是否可行,但它在桌面应用程序中有效。尝试使用 ConfigurationSettings 而不是 ConfigurationManager(它会因为使用过时的类而对你大喊大叫......),然后将所有数据读入一个类。当您希望刷新时,只需创建一个新实例并删除对旧实例的所有引用。我的理论为什么会这样(可能是错误的):当您在整个运行过程中没有直接访问 app.config 文件时,应用程序会删除文件锁定。然后,可以在您不访问文件时进行编辑。
回答by Martin Meixger
As an alternative you could write your own ConfigSection
and set restartOnExternalChanges="false"
.
作为替代方案,您可以编写自己的ConfigSection
并设置restartOnExternalChanges="false"
.
Then, when reading the section with ConfigurationManager.GetSection("yourSection")
the settings will be auto-refreshed without an application restart.
然后,在阅读带有ConfigurationManager.GetSection("yourSection")
设置的部分时将自动刷新,而无需重新启动应用程序。
And you could implement your settings strongly typed or as NameValueCollection.
你可以实现你的设置强类型或作为 NameValueCollection。
回答by Willem van Ketwich
For some reason ConfigurationManager.RefreshSection("appSettings")
wasn't working for me. Reloading the Web.Config into a Configuration object seems to work correctly. The following code assumes the Web.Config file is one directory below the executing (bin) folder.
由于某种原因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);
And is used like:
并使用如下:
string webConfigVariable = config.AppSettings.Settings["webConfigVariable"].Value;
回答by Allie
.RefreshSection() does not work when the appSettings is external.
当 appSettings 是外部的时,.RefreshSection() 不起作用。
You can however use the following to change a value:
但是,您可以使用以下内容来更改值:
ConfigurationManager.AppSettings.Set(key, value)
This will NOT change the setting on file, only the loaded value in memory.
这不会更改文件中的设置,只会更改内存中的加载值。
So instead of using RefreshSection I did the following:
因此,我没有使用 RefreshSection,而是执行了以下操作:
string configFile="path to your config file";
XmlDocument xml = new XmlDocument();
xml.Load(configFile);
foreach (XmlNode node in xml.SelectNodes("/appSettings/add"))
{
string key = node.Attributes["key"].Value;
string value= node.Attributes["value"].Value;
ConfigurationManager.AppSettings.Set(key, value);
}
Any subsequent calls to AppSettings.Get will contain the updated value.
对 AppSettings.Get 的任何后续调用都将包含更新后的值。
The appSettings will then be updated without needing to restart the application.
然后无需重新启动应用程序即可更新 appSettings。