如何更新(添加/修改/删除)键在运行时的web.config的appSettings部分(How t

2019-07-28 02:50发布

我喜欢更新定义的键/值AppSettings部分Web.config在运行时。 但是我不想真正将它们保存到Web.config文件。

我有有由许多模块,DLL和源代码文件的一个巨大的Web应用程序。 的关键信息的一束从数据库配置,加密密钥,用户名和范围为web服务的密码保存在AppSettings所述的部分web.config文件。 最近的项目需求需要我将这些值出的web.config ,并保持在一个安全的存储。

我已经在外部位置固定这些价值和应用程序启动时我能读懂他们。

这里是示例代码。

Global.asax中

public class Global: System.Web.HttpApplication {
    protected void Application_Start(object sender, EventArgs e) {
        Dictionary<string, string> secureConfig = new Dictionary<string,string>{};

        // --------------------------------------------------------------------
        // Here I read and decrypt keys and add them to secureConfig dictionary
        // To test assume the following line is a key stored in secure sotrage.
        //secureConfig = SecureConfig.LoadConfig();
        secureConfig.Add("ACriticalKey","VeryCriticalValue");
        // --------------------------------------------------------------------

        foreach (KeyValuePair<string, string> item in secureConfig) {
            ConfigurationManager.AppSettings.Add(item.Key, item.Value);
        }
    }
}

正如你可能会注意到它是不可行的改变引用AppSettings通过多种编程团队创造了一个巨大的代码从我读它们的设置secureConfig dictionary ,并在另一方面,我不应该保存在这些值web.config文件,该文件是提供给网络管理员和操作员,系统管理员和管理员的云。

为了让程序员的生活更轻松,我想让他们自己添加值AppSettings部分web.config开发过程中,但他们会从那里被删除,并把后来在部署期间安全储存,但是这些值应提供透明的程序他们仍然在AppSettings部分。

:我怎么能添加值AppSettings在运行时使程序可以使用阅读ConfigurationManager.AppSettings["ACriticalKey"]获得"VeryCriticalValue"而不保存Web.Config中?

请注意ConfigurationManager.AppSettings.Add(item.Key, item.Value); 给我ConfigurationErrorsException与消息The configuration is read only.

请注意 :最好的一些设置应该能够留在AppSettings像以前一样

Answer 1:

我知道这是一个老问题,但我遇到了同样的问题,我发现,设置工作在相同的方式添加,并没有抛出异常,所以只需更换添加与设置,如下所示:

ConfigurationManager.AppSettings.Set(item.Key, item.Value);


Answer 2:

你需要使用WebConfigurationManager.OpenWebConfiguration()

Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
config.AppSettings.Settings.Remove("Variable");
config.AppSettings.Settings.Add("Variable", "valyue");
config.Save();


Answer 3:

也许这个链接会有所帮助。 它引用了2.0,但我相信,方法仍是4.0无效。

此外,在相同/相似的话题SO问题, 这里可能有兴趣。

此外,在运行时修改web.config中应该会导致应用程序池每次回收。 不是要告诉你如何班门弄斧,只是觉得应该注意它的任何人的预期利益... THX。



Answer 4:

由于nkvu其指示我这反过来把我送到他的第一个链接Williarob的帖子‘ 重写配置管理器 ’我设法找到一个解决我的问题。

所提到的博客文章介绍如何从另一个XML文件中读取设置,并将其与两个窗口的应用程序和Web应用程序(在配置文件名和路径稍加修改)的作品。 虽然这个博客2010年写它仍然工作正常与.NET4没有问题。

然而,由于我打算从安全设备读取我的配置,我简化了类,这里是如何使用提供的类Williarob

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Internal;
using System.Linq;
using System.Reflection;

namespace Williablog.Core.Configuration {

    public sealed class ConfigSystem: IInternalConfigSystem {
        private static IInternalConfigSystem clientConfigSystem;

        private object appsettings;

        private object connectionStrings;

        /// <summary>
        /// Re-initializes the ConfigurationManager, allowing us to merge in the settings from Core.Config
        /// </summary>
        public static void Install() {
            FieldInfo[] fiStateValues = null;
            Type tInitState = typeof(System.Configuration.ConfigurationManager).GetNestedType("InitState", BindingFlags.NonPublic);

            if (null != tInitState) {
                fiStateValues = tInitState.GetFields();
            }

            FieldInfo fiInit = typeof(System.Configuration.ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static);
            FieldInfo fiSystem = typeof(System.Configuration.ConfigurationManager).GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static);

            if (fiInit != null && fiSystem != null && null != fiStateValues) {
                fiInit.SetValue(null, fiStateValues[1].GetValue(null));
                fiSystem.SetValue(null, null);
            }

            ConfigSystem confSys = new ConfigSystem();
            Type configFactoryType = Type.GetType("System.Configuration.Internal.InternalConfigSettingsFactory, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true);
            IInternalConfigSettingsFactory configSettingsFactory = (IInternalConfigSettingsFactory) Activator.CreateInstance(configFactoryType, true);
            configSettingsFactory.SetConfigurationSystem(confSys, false);

            Type clientConfigSystemType = Type.GetType("System.Configuration.ClientConfigurationSystem, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true);
            clientConfigSystem = (IInternalConfigSystem) Activator.CreateInstance(clientConfigSystemType, true);
        }

        #region IInternalConfigSystem Members
        public object GetSection(string configKey) {
            // get the section from the default location (web.config or app.config)
            object section = clientConfigSystem.GetSection(configKey);

            switch (configKey) {
                case "appSettings":
                    // Return cached version if exists
                    if (this.appsettings != null) {
                        return this.appsettings;
                    }

                    // create a new collection because the underlying collection is read-only
                    var cfg = new NameValueCollection();

                    // If an AppSettings section exists in Web.config, read and add values from it
                    if (section is NameValueCollection) {
                        NameValueCollection localSettings = (NameValueCollection) section;
                        foreach (string key in localSettings) {
                            cfg.Add(key, localSettings[key]);
                        }
                    }

                    // --------------------------------------------------------------------
                    // Here I read and decrypt keys and add them to secureConfig dictionary
                    // To test assume the following line is a key stored in secure sotrage.
                    //secureConfig = SecureConfig.LoadConfig();
                    secureConfig.Add("ACriticalKey", "VeryCriticalValue");
                    // --------------------------------------------------------------------                        
                    foreach (KeyValuePair<string, string> item in secureConfig) {
                        if (cfg.AllKeys.Contains(item.Key)) {
                            cfg[item.Key] = item.Value;
                        } else {
                            cfg.Add(item.Key, item.Value);
                        }
                    }
                    // --------------------------------------------------------------------                        


                    // Cach the settings for future use
                    this.appsettings = cfg;
                    // return the merged version of the items from secure storage and appsettings
                    section = this.appsettings;
                    break;

                case "connectionStrings":
                    // Return cached version if exists
                    if (this.connectionStrings != null) {
                        return this.connectionStrings;
                    }

                    // create a new collection because the underlying collection is read-only
                    ConnectionStringsSection connectionStringsSection = new ConnectionStringsSection();

                    // copy the existing connection strings into the new collection
                    foreach (ConnectionStringSettings connectionStringSetting in ((ConnectionStringsSection) section).ConnectionStrings) {
                        connectionStringsSection.ConnectionStrings.Add(connectionStringSetting);
                    }

                    // --------------------------------------------------------------------
                    // Again Load connection strings from secure storage and merge like below
                    // connectionStringsSection.ConnectionStrings.Add(connectionStringSetting);
                    // --------------------------------------------------------------------                        

                    // Cach the settings for future use
                    this.connectionStrings = connectionStringsSection;
                    // return the merged version of the items from secure storage and appsettings
                    section = this.connectionStrings;
                    break;
            }

            return section;
        }

        public void RefreshConfig(string sectionName) {
            if (sectionName == "appSettings") {
                this.appsettings = null;
            }

            if (sectionName == "connectionStrings") {
                this.connectionStrings = null;
            }

            clientConfigSystem.RefreshConfig(sectionName);
        }

        public bool SupportsUserConfig { get { return clientConfigSystem.SupportsUserConfig; } }

        #endregion
    }
}

要安装此(配置覆盖或原始版本)以下行添加到您的全局。 在的Application_Start类(Global.asax.cs中)

Williablog.Core.Configuration.ConfigSystem .Install();

如下图所示:

public class Global: System.Web.HttpApplication {

    //...

    #region protected void Application_Start(...)
    protected void Application_Start(object sender, EventArgs e) {
        Williablog.Core.Configuration.ConfigSystem .Install();

        //...

    }
    #endregion

    //...

}


文章来源: How to Update (Add/Modify/Delete) keys in AppSettings section of web.config at runtime