问题
I have a subfolder in my web application. It's not a separate application, just a subfolder, but it has its own web.config. There is an aspx page in that subfolder which needs to access a setting in the web.config file in its own folder.
When I call ConfigurationManager.GetSection("settingname") from a static initializer on that aspx page, it returns null. Why might this happen? Could it be that my setting name is wrong or that the application root web.config is being accessed instead of the subfolder's web.config?
回答1:
If you want programmatic access to ConnectionStrings, AppSettings or anything else in a web.config file other than in the root of the application then you need to use the WebConfigurationManager class in the System.Web.Configuration namespace (see http://msdn.microsoft.com/en-us/library/system.web.configuration.webconfigurationmanager.aspx) instead of the ConfigurationManager class in the System.Configuration namespace. This should resolve your problem.
From MSDN-
"Using WebConfigurationManager is the preferred way to work with configuration files related to Web applications. For client applications, use the ConfigurationManager class."
I understand (although I can't cite this as fact) that the ConfigurationManager class was designed for Windows Forms applications where I believe there is only a single App.config file.
来源:https://stackoverflow.com/questions/15162980/how-to-retrieve-web-config-setting-in-web-application-subfolder