How do you modify the web.config appSettings at runtime?

后端 未结 7 1709
小鲜肉
小鲜肉 2020-11-22 14:28

I am confused on how to modify the web.config appSettings values at runtime. For example, I have this appSettings section:


  

        
相关标签:
7条回答
  • 2020-11-22 14:35

    Changing the web.config generally causes an application restart.

    If you really need your application to edit its own settings, then you should consider a different approach such as databasing the settings or creating an xml file with the editable settings.

    0 讨论(0)
  • 2020-11-22 14:43

    2012 This is a better solution for this scenario (tested With Visual Studio 2008):

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

    Update 2018 =>
    Tested in vs 2015 - Asp.net MVC5

    var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
    config.AppSettings.Settings["MyVariable"].Value = "MyValue";
    config.Save();
    

    if u need to checking element exist, use this code:

    var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
    if (config.AppSettings.Settings["MyVariable"] != null)
    {
    config.AppSettings.Settings["MyVariable"].Value = "MyValue";
    }
    else { config.AppSettings.Settings.Add("MyVariable", "MyValue"); }
    config.Save();
    
    0 讨论(0)
  • 2020-11-22 14:48

    I know this question is old, but I wanted to post an answer based on the current state of affairs in the ASP.NET\IIS world combined with my real world experience.

    I recently spearheaded a project at my company where I wanted to consolidate and manage all of the appSettings & connectionStrings settings in our web.config files in one central place. I wanted to pursue an approach where our config settings were stored in ZooKeeper due to that projects maturity & stability. Not to mention that fact that ZooKeeper is by design a configuration & cluster managing application.

    The project goals were very simple;

    1. get ASP.NET to communicate with ZooKeeper
    2. in Global.asax, Application_Start - pull web.config settings from ZooKeeper.

    Upon getting passed the technical piece of getting ASP.NET to talk to ZooKeeper, I quickly found and hit a wall with the following code;

    ConfigurationManager.AppSettings.Add(key_name, data_value)
    

    That statement made the most logical sense since I wanted to ADD new settings to the appSettings collection. However, as the original poster (and many others) mentioned, this code call returns an Error stating that the collection is Read-Only.

    After doing a bit of research and seeing all the different crazy ways people worked around this problem, I was very discouraged. Instead of giving up or settling for what appeared to be a less than ideal scenario, I decided to dig in and see if I was missing something.

    With a little trial and error, I found the following code would do exactly what I wanted;

    ConfigurationManager.AppSettings.Set(key_name, data_value)
    

    Using this line of code, I am now able to load all 85 appSettings keys from ZooKeeper in my Application_Start.

    In regards to general statements about changes to web.config triggering IIS recycles, I edited the following appPool settings to monitor the situation behind the scenes;

    appPool-->Advanced Settings-->Recycling-->Disable Recycling for Configuration Changes = False
    appPool-->Advanced Settings-->Recycling-->Generate Recycle Event Log Entry-->[For Each Setting] = True
    

    With that combination of settings, if this process were to cause an appPool recycle, an Event Log entry should have be recorded, which it was not.

    This leads me to conclude that it is possible, and indeed safe, to load an applications settings from a centralized storage medium.

    I should mention that I am using IIS7.5 on Windows 7. The code will be getting deployed to IIS8 on Win2012. Should anything regarding this answer change, I will update this answer accordingly.

    0 讨论(0)
  • 2020-11-22 14:49

    Try This:

    using System;
    using System.Configuration;
    using System.Web.Configuration;
    
    namespace SampleApplication.WebConfig
    {
        public partial class webConfigFile : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                //Helps to open the Root level web.config file.
                Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
                //Modifying the AppKey from AppValue to AppValue1
                webConfigApp.AppSettings.Settings["ConnectionString"].Value = "ConnectionString";
                //Save the Modified settings of AppSettings.
                webConfigApp.Save();
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 14:52

    And if you want to avoid the restart of the application, you can move out the appSettings section:

    <appSettings configSource="Config\appSettings.config"/>
    

    to a separate file. And in combination with ConfigurationSaveMode.Minimal

    var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
    config.Save(ConfigurationSaveMode.Minimal);
    

    you can continue to use the appSettings section as the store for various settings without causing application restarts and without the need to use a file with a different format than the normal appSettings section.

    0 讨论(0)
  • 2020-11-22 14:57

    You need to use WebConfigurationManager.OpenWebConfiguration(): For Example:

    Dim myConfiguration As Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
    myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text
    myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text
    myConfiguration.Save()
    

    I think you might also need to set AllowLocation in machine.config. This is a boolean value that indicates whether individual pages can be configured using the element. If the "allowLocation" is false, it cannot be configured in individual elements.

    Finally, it makes a difference if you run your application in IIS and run your test sample from Visual Studio. The ASP.NET process identity is the IIS account, ASPNET or NETWORK SERVICES (depending on IIS version).

    Might need to grant ASPNET or NETWORK SERVICES Modify access on the folder where web.config resides.

    0 讨论(0)
提交回复
热议问题