2011-03-06 75 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的成本。

相關問題