Web.config save problem

2019-06-23 18:37发布

问题:

I want to expose some of the web.config settings to a user via the front end of the web app. I can retrieve the settings without a problem, but when I save I either get an error or the changes are not persisted to the web.config file. I am debugging in VS.

If I run this:

    private void SaveWebConfig()
    {
        Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~//Web.config");
        webConfig.AppSettings.Settings["DocumentPath"].Value = this.txtDocumentsDirectory.Text;
        webConfig.Save();
    }

I get the following error: A configuration file cannot be created for the requested Configuration object.

If I run this code, nothing happens:

 private void SaveWebConfig()
 {
     Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~//Web.config");
     webConfig.AppSettings.Settings["DocumentPath"].Value = this.txtDocumentsDirectory.Text;
     webConfig.SaveAs("~//Web.config");
 }

回答1:

It can be done, and it is rather easy. Whether it works depends on the privileges of the user account that your App runs under.

You are using double forward slashes, and the SaveAs is wrong too. Try:

 private void SaveWebConfig()
 {
     Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~");
     webConfig.AppSettings.Settings["DocumentPath"].Value =
          this.txtDocumentsDirectory.Text;
     webConfig.Save();
 }

But you probably should avoid changing the (root) web.config as much as possible. I've only seen this in special pages for the SiteManager to make config changes.



回答2:

To my knowledge the web.config should not be altered by the consuming web application. ASP.NET and IIS are built to restart the whole application every time the web.config is updated.

Instead of exposing it expose settings from the database and persist these settings in the db, your front end should not change much only the way you load and save data does.