开发者

ASP.net why can't I access this web.config key?

开发者 https://www.devze.com 2023-02-15 07:45 出处:网络
public partial class MasterPages_Main : System.Web.UI.MasterPage { public string TopMenuTab; public string SubMenuTab;
public partial class MasterPages_Main : System.Web.UI.MasterPage
{
    public string TopMenuTab;
    public string SubMenuTab;
    public Configuration Config = WebConfigurationManager.OpenWebConfiguration(null);

开发者_C百科    protected void Page_Load(object sender, EventArgs e)
    {
        ContentMenu.TopTabSelected = TopMenuTab;
        ContentMenu.SubTabSelected = SubMenuTab;

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

}

In web.config:

<appSettings>

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

I get:

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

On the response.write line


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

do a null check and then call ToString() or Convert.ToInt32()


ConfigurationSettings.AppSettings is the correct approach.

You don't need the Config object. You only need to use OpenWebConfiguration if you're going to write to the web.config file. It isn't needed just to read the config data.

Edit: When any .Net application starts, its config file data is read into memory and cached there for the lifetime of the app. The general assumption is that the config data will be used enough to warrant this use of memory, and that it will be worthwhile to avoid the cost of opening the file and reading the XML every time config information is needed by the app.

0

精彩评论

暂无评论...
验证码 换一张
取 消