C# ASP.net为什么可以';我不能访问这个web.config密钥吗?
在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
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"];