Web 配置每分钟自动更换一次

webconfig is replaced every minute automatically

我的要求是在应用程序启动时 运行 更新 appsettings 文件。但是遇到了一个问题,即每分钟都会用新的应用程序设置替换 Web 配置。我怎样才能停止每分钟更换一次?

我在这里经历了不同的解决方案并实现如下:

  1. 在网络配置中,我们有应用程序设置的默认路径:
 appSettings file="C:\Config\MyProj\Appsettings.Config" 
  1. 在 Global.asax.cs 中,我正在调用以下方法动态替换我的应用程序设置文件。

    public void ChangeAppSettings(string path)
    {
        System.Configuration.Configuration configuration = null;
        if (System.Web.HttpContext.Current != null)
        {
            configuration =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
        }
        else
        {
            configuration =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        }
        // update appconfig file path
        configuration.AppSettings.File = path;

        // Save the configuration file.
        configuration.Save(ConfigurationSaveMode.Modified);

        // Force a reload in memory of the changed section.
        ConfigurationManager.RefreshSection("appSettings");
    }

或者有更好的实现方式吗?

以下代码成功了,出于某种原因,每次我们刷新配置时都会调用 ChangeAppSettings 方法。所以我只是添加了检查配置是否已经修改然后不再刷新。

if (!path.Equals(configuration.AppSettings.File))

{
    // update appconfig file path

    configuration.AppSettings.File = path;

    // Save the configuration file.

    configuration.Save(ConfigurationSaveMode.Modified);

    // Force a reload in memory of the changed section.

    ConfigurationManager.RefreshSection("appSettings");

}