使用System.Configuration.ConfigurationSection保存对web.config的更改

时间:2014-06-12 17:38:48

标签: c# .net web-config webconfigurationmanager

我创建了一个自定义Web配置部分,我可以在运行时成功读取和修改。但是,它不会物理更改web.config。如果站点重新启动或池被回收,我将丢失更改并恢复为原始web.config设置。

我希望能够将更改保留到web.config文件中,但我无法解决这个问题。

我的web.config部分如下所示:

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

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

这是我的配置类

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

在我的控制器中,我使用已发布的表单修改设置

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

在config类的save方法中,IsModified()返回true,现在我只需要对文件进行修改。

1 个答案:

答案 0 :(得分:1)

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

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

我只是从最佳做法的角度提问,因为我知道这是可能的,只是不推荐。

相关问题