Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.net为什么可以';我不能访问这个web.config密钥吗?_C#_Asp.net_Web Config - Fatal编程技术网

C# ASP.net为什么可以';我不能访问这个web.config密钥吗?

C# ASP.net为什么可以';我不能访问这个web.config密钥吗?,c#,asp.net,web-config,C#,Asp.net,Web Config,在web.config中: public partial class MasterPages_Main : System.Web.UI.MasterPage { public string TopMenuTab; public string SubMenuTab; public Configuration Config = WebConfigurationManager.OpenWebConfiguration(null); protected void Pag

在web.config中:

public partial class MasterPages_Main : System.Web.UI.MasterPage
{
    public string TopMenuTab;
    public string SubMenuTab;
    public Configuration Config = WebConfigurationManager.OpenWebConfiguration(null);

    protected void Page_Load(object sender, EventArgs e)
    {
        ContentMenu.TopTabSelected = TopMenuTab;
        ContentMenu.SubTabSelected = SubMenuTab;

        Response.Write("K" + Config.AppSettings.Settings["BlogCommentsPerPage"].ToString());
    }

}
在response.write行上

System.NullReferenceException: Object reference not set to an instance of an object.

执行空检查,然后调用
ToString()
Convert.ToInt32()
ConfigurationSettings。AppSettings
是正确的方法

您不需要
Config
对象。如果要写入
web.config
文件,只需使用
OpenWebConfiguration
。不需要只读取配置数据

编辑:当任何.Net应用程序启动时,其配置文件数据将被读入内存,并在应用程序的生命周期内缓存在内存中。一般的假设是,配置数据的使用将足以保证内存的使用,并且每次应用程序需要配置信息时,都有必要避免打开文件和读取XML的成本

System.NullReferenceException: Object reference not set to an instance of an object.
var commentsPerPage = ConfigurationSettings.AppSettings["BlogCommentsPerPage"];