如何修改web。在运行时配置appSettings吗?

时间:2022-11-06 20:21:12

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

我对如何修改web感到困惑。配置在运行时appSettings值。例如,我有这个appSettings部分:

<appSettings>
  <add key="productspagedesc" value="TODO: Edit this default message" />
  <add key="servicespagedesc" value="TODO: Edit this default message" />
  <add key="contactspagedesc" value="TODO: Edit this default message" />
  <add key="aboutpagedesc" value="TODO: Edit this default message" />
  <add key="homepagedesc" value="TODO: Edit this default message" />
 </appSettings>

Let's say, I want to modify the "homepagedesc" key at runtime. I tried ConfigurationManager and WebConfigurationManager static classes, but the settings are "read-only". How do I modify appSettings values at runtime?

比方说,我想在运行时修改“主页desc”键。我尝试了ConfigurationManager和WebConfigurationManager静态类,但是这些设置都是“只读的”。如何在运行时修改appSettings值?

UPDATE: Ok, so here I am 5 years later. I would like to point out that experience has told me, we should not put any configuration that intentionally is editable at runtime in the web.config file but instead we should put it in a separate XML file as what one of the users commented below. This will not require any of edit of web.config file to restart the App which will result with angry users calling you.

更新:好的,我在这里5年之后。我想指出的是,经验告诉我,我们不应该在web的运行时放置任何有意可编辑的配置。配置文件,但是我们应该把它放在一个单独的XML文件中,就像下面的用户评论的那样。这将不需要任何网络编辑。配置文件重新启动应用程序,这将导致愤怒的用户打电话给你。

7 个解决方案

#1


77  

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

您需要使用WebConfigurationManager.OpenWebConfiguration():例如:

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.

我认为您可能还需要在machine.config中设置允许值。这是一个布尔值,指示是否可以使用元素配置单个页面。如果“allowLocation”为false,则不能在单个元素中配置它。

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).

最后,如果您在IIS中运行应用程序,并从Visual Studio中运行测试示例,则会产生不同的结果。ASP。NET进程标识是IIS帐户、ASPNET或网络服务(取决于IIS版本)。

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

可能需要授予ASPNET或网络服务修改对web所在文件夹的访问权限。配置驻留。

#2


23  

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.

如果您确实需要应用程序编辑自己的设置,那么您应该考虑一种不同的方法,例如数据库设置或使用可编辑设置创建一个xml文件。

#3


21  

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

如果您想避免重新启动应用程序,可以将appSettings部分移出:

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

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

一个单独的文件。并结合了configurationsavemode .最少。

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.

您可以继续使用appSettings部分作为各种设置的存储,而不会导致应用程序重新启动,也不需要使用与常规appSettings部分不同格式的文件。

#4


17  

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

2012年,这是这个场景的更好的解决方案(使用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

更新2018 =>测试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();

#5


12  

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.

我知道这个问题已经过时了,但是我想根据ASP中的当前情况发布一个答案。NET\IIS世界结合我的真实世界经验。

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.

我最近在我的公司领导了一个项目,在这个项目中,我想合并和管理我们的web中的所有appSettings & connectionStrings设置。在一个中心位置配置文件。由于项目的成熟度和稳定性,我希望采用一种方法,将配置设置存储在ZooKeeper中。更不用说,ZooKeeper是通过设计一个配置和集群管理应用程序实现的。

The project goals were very simple;

项目目标非常简单;

  1. get ASP.NET to communicate with ZooKeeper
  2. ASP。与动物园管理员沟通
  3. in Global.asax, Application_Start - pull web.config settings from ZooKeeper.
  4. 在全球。asax, Application_Start - pull web。从动物园管理员配置设置。

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;

通过了获得ASP的技术部分。网与动物园管理员交谈时,我很快找到了一堵墙,并按下了下面的代码;

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.

这条语句非常符合逻辑,因为我想向appSettings集合添加新的设置。但是,正如最初的poster(以及许多其他的)所提到的,此代码调用返回一个错误,指出集合是只读的。

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.

使用这行代码,我现在可以在我的Application_Start中从ZooKeeper加载所有85个appSettings键。

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;

关于web更改的一般声明。配置触发IIS回收,我编辑了下面的appPool设置来监控幕后的情况;

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.

有了这些设置的组合,如果该进程要导致appPool回收,则应该记录一个事件日志条目,但事实并非如此。

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.

我应该提一下,我正在Windows 7上使用IIS7.5。该代码将在2012年部署到IIS8。如果这个答案有任何变化,我会相应地更新这个答案。

#6


2  

Who likes directly to the point,

谁喜欢直截了当,

In your Config

在你的配置

    <appSettings>

    <add key="Conf_id" value="71" />

  </appSettings>

in your code(c#)

在你的代码(c#)

///SET
    ConfigurationManager.AppSettings.Set("Conf_id", "whateveryourvalue");
      ///GET              
    string conf = ConfigurationManager.AppSettings.Get("Conf_id").ToString();

#7


0  

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();
        }
    }
}

#1


77  

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

您需要使用WebConfigurationManager.OpenWebConfiguration():例如:

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.

我认为您可能还需要在machine.config中设置允许值。这是一个布尔值,指示是否可以使用元素配置单个页面。如果“allowLocation”为false,则不能在单个元素中配置它。

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).

最后,如果您在IIS中运行应用程序,并从Visual Studio中运行测试示例,则会产生不同的结果。ASP。NET进程标识是IIS帐户、ASPNET或网络服务(取决于IIS版本)。

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

可能需要授予ASPNET或网络服务修改对web所在文件夹的访问权限。配置驻留。

#2


23  

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.

如果您确实需要应用程序编辑自己的设置,那么您应该考虑一种不同的方法,例如数据库设置或使用可编辑设置创建一个xml文件。

#3


21  

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

如果您想避免重新启动应用程序,可以将appSettings部分移出:

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

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

一个单独的文件。并结合了configurationsavemode .最少。

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.

您可以继续使用appSettings部分作为各种设置的存储,而不会导致应用程序重新启动,也不需要使用与常规appSettings部分不同格式的文件。

#4


17  

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

2012年,这是这个场景的更好的解决方案(使用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

更新2018 =>测试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();

#5


12  

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.

我知道这个问题已经过时了,但是我想根据ASP中的当前情况发布一个答案。NET\IIS世界结合我的真实世界经验。

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.

我最近在我的公司领导了一个项目,在这个项目中,我想合并和管理我们的web中的所有appSettings & connectionStrings设置。在一个中心位置配置文件。由于项目的成熟度和稳定性,我希望采用一种方法,将配置设置存储在ZooKeeper中。更不用说,ZooKeeper是通过设计一个配置和集群管理应用程序实现的。

The project goals were very simple;

项目目标非常简单;

  1. get ASP.NET to communicate with ZooKeeper
  2. ASP。与动物园管理员沟通
  3. in Global.asax, Application_Start - pull web.config settings from ZooKeeper.
  4. 在全球。asax, Application_Start - pull web。从动物园管理员配置设置。

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;

通过了获得ASP的技术部分。网与动物园管理员交谈时,我很快找到了一堵墙,并按下了下面的代码;

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.

这条语句非常符合逻辑,因为我想向appSettings集合添加新的设置。但是,正如最初的poster(以及许多其他的)所提到的,此代码调用返回一个错误,指出集合是只读的。

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.

使用这行代码,我现在可以在我的Application_Start中从ZooKeeper加载所有85个appSettings键。

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;

关于web更改的一般声明。配置触发IIS回收,我编辑了下面的appPool设置来监控幕后的情况;

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.

有了这些设置的组合,如果该进程要导致appPool回收,则应该记录一个事件日志条目,但事实并非如此。

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.

我应该提一下,我正在Windows 7上使用IIS7.5。该代码将在2012年部署到IIS8。如果这个答案有任何变化,我会相应地更新这个答案。

#6


2  

Who likes directly to the point,

谁喜欢直截了当,

In your Config

在你的配置

    <appSettings>

    <add key="Conf_id" value="71" />

  </appSettings>

in your code(c#)

在你的代码(c#)

///SET
    ConfigurationManager.AppSettings.Set("Conf_id", "whateveryourvalue");
      ///GET              
    string conf = ConfigurationManager.AppSettings.Get("Conf_id").ToString();

#7


0  

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();
        }
    }
}