1

I have created a custom web config section that I can read and modify successfully at runtime. However, it does not physically change the web.config. If the site is restarted or the pool is recycled I lose my changes and it reverts to the original web.config settings.

I would like to be able to persist the changes to the web.config file and I have not been able to figure this out.

My web.config section looks like this:

<configSections>
    <section
        name="MyCustomConfig"
        type="MyProject.Configuration.myCustomConfig"
        allowLocation="true"
        allowDefinition="Everywhere"
        /> 
</configSections>

<MyCustomConfig Address="127.0.0.1" 
        OrgId="myorg" 
        User="john"/>

Here is my configuration class

namespace MyProject.Configuration
{
    public class MyCustomConfig : System.Configuration.ConfigurationSection
    {
        // Static accessor
        public static MyCustomConfig Current =
            (MyCustomConfig)WebConfigurationManager.GetSection("MyCustomConfig");

        public void Save()
        {
            if (IsModified())
            {
                // I'm getting here, but can't figure out how to save

            }

        }

        public override bool IsReadOnly()
        {
            return false;

        }

        [ConfigurationProperty("OrgId", DefaultValue = "test", IsRequired = true)]
        public string OrgId
        {
            get { return this["OrgId"].ToString(); }
            set { 
                this["OrgId"] = value; 
            }
        }
        [ConfigurationProperty("Address", DefaultValue="127.0.0.1", IsRequired=true)]
        public string Address {
            get { return this["Address"].ToString();  }
            set { this["Address"] = value; }
        }

        [ConfigurationProperty("User", DefaultValue = "", IsRequired = true)]
        public string User
        {
            get {
                if (this["User"] == null) return string.Empty;
                else return this["User"].ToString(); 
            }
            set { this["User"] = value; }
        }
    }
}

In my controller, I modify the settings with the posted form

[HttpPost]
public ActionResult Edit(ConfigurationViewModel config)
{

    if (ModelState.IsValid)
    {
        // write changes to web.config
        Configuration.MyCustomConfig.Current.Address = config.SIPAddress;
        Configuration.MyCustomConfig.Current.User = config.User;
        Configuration.MyCustomConfig.Current.OrgId = config.OrgId;
        Configuration.MyCustomConfig.Save()
    }
}

In the config class save method, IsModified() returns true, now I just need to get those modifications to file.

4

1 回答 1

1

为什么要在运行时更改配置文件?这将导致每次对文件进行更改时应用程序池回收。

将这些设置存储在数据库中并在应用程序启动时从数据库中恢复它们是否有意义?

我只是从最佳实践的角度提出质疑,因为我知道这是可能的,只是不推荐。

于 2014-06-12T17:47:49.797 回答