【问题标题】:Programmatically setting Web.Config AppSettings in .NET Web Forms以编程方式在 .NET Web 窗体中设置 Web.Config AppSettings
【发布时间】:2019-10-02 03:44:21
【问题描述】:

使用一系列网站,通过简单地循环访问存储在数据库中的用户指定值,以编程方式为每个网站设置一些 appSettings 值。

foreach (DataRow dr in result.Tables[0].Rows) {
    ConfigurationManager.AppSettings.Set(dr["app_key_name"].ToString(), dr["app_key_value"].ToString());
}

这允许每个站点使用相同的代码库,但定义和访问不同的变量。

问题是一个(许多)网站似乎经常丢失以编程方式添加的 appSettings。在 Web.Config 文件中设置的少数 appSettings 仍然存在,但以编程方式添加的 appSettings 有时似乎会失败,或者在站点回收时不会重新加载。

是否应该在 Application_BeginRequest 上检查这些变量,如果它们不存在则重新添加?想法?

【问题讨论】:

    标签: c# asp.net .net webforms


    【解决方案1】:

    你不需要调用 Save() 吗?:

        config.Save(System.Configuration.ConfigurationSaveMode.Modified)
    

    【讨论】:

    • 这些是动态添加的,实际上并未写入物理 web.config 文件。
    • “当网站回收” - 是的,价值将会丢失。
    • 如何添加自定义,如下所示:public class CustomConfig { private static System.Collections.Specialized.NameValueCollection _AppSettings = null; public static System.Collections.Specialized.NameValueCollection AppSettings { get { if (_AppSettings == null) { _AppSettings = System.Configuration.ConfigurationManager.AppSettings; } return _AppSettings; } } }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    相关资源
    最近更新 更多