2011-03-06 76 views
1
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()); 
    } 

} 

在web.config中:ASP.net为什么我无法访问此web.config密钥?

<appSettings> 

    <!-- Website settings --> 
    <add key="BlogCommentsPerPage" value="3" /> 

我得到:

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

在的Response.Write行

回答

1
var commentsPerPage = ConfigurationSettings.AppSettings["BlogCommentsPerPage"]; 

做一个空检查,然后调用ToString()Convert.ToInt32()

1

ConfigurationSettings.AppSettings是正确的方法。

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

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

相关问题