【问题标题】:How to save configurations into web.config file?如何将配置保存到 web.config 文件中?
【发布时间】:2016-08-04 14:21:18
【问题描述】:

我正在使用 Asp.net 动态网站应用程序,无法将配置保存到 web.config 文件中。

我尝试过类似的方法,但不起作用!

 var configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

        configuration.AppSettings.Settings["Value"].Value = "Some value";
        configuration.Save();

我遇到的错误

1. OpenWebConfiguration(Server.MapPath(".")) & OpenWebConfiguration(Server.MapPath("~"):

The relative virtual path 'C:/...' is not allowed here.

2. OpenWebConfiguration("~")

    An error occurred loading a configuration file: Failed to map the path '/'.

我真的不知道该怎么办了。

【问题讨论】:

  • 您不想在运行时修改您的 Web 配置。您将强制您的应用程序池/Web 应用程序重新启动执行此操作,结果您将丢失所有会话并在下一次请求时产生开销。相反,您希望将此数据持久保存到数据库中的表中。

标签: asp.net web-config save


【解决方案1】:

documentation 开始,它指出为路径传递空值将打开默认的 web.config 文件。
查看您的代码,您实际上并没有在路径中指定配置文件名。

所以使用:

    OpenWebConfiguration(null)

编辑:好的。我已经做了一些进一步的调查,传入 null 将访问 C:\Windows\Microsoft.NET\Framework\v2.0.50727\Config 文件夹中的服务器默认 web.config 文件,在这种情况下这不是你想要的。
传递“~”应该可以让您访问 Web 应用程序的默认 web.config 文件,我已经在 Visual Studio 2008 中使用 .NET 3.5 使用以下代码成功测试了这一点:

    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
    config.AppSettings.Settings["test"].Value = "Hello";
    config.Save();

我不确定为什么这对您的情况不起作用。我建议在您创建配置对象的代码行放置一个断点,并使用 Visual Studio IDE 中的“即时窗口”来调用 WebConfigurationManager 的静态 OpenWebConfiguration 方法,以查看可以获得的结果。输入 WebConfigurationManager.OpenWebConfiguration("~").AppSettings.Settings.AllKeys 之类的内容应表明您是否成功访问了 web.config。

【讨论】:

  • Null 有帮助,但在下一行我收到错误“对象引用未设置为对象的实例。”,因为未读取键。
  • 你能给出你的 web.config 的真实例子(只有一个值)和读取它的代码吗?
  • 配置文件: 这是我的配置文件的例子。
【解决方案2】:

使用下面的代码。

configuration.Save(ConfigurationSaveMode.Full, true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多