WebConfigurationManager 和 ConfigurationManager 有什麼不同?

  • 2631
  • 0

摘要:WebConfigurationManager 和 ConfigurationManager 有什麼不同?

文章引用

 

uses System.Web.Configuration;
[...]
Console.WriteLine(WebConfigurationManager.ConnectionStrings["MyConnStr"].ConnectionString);

Note that this will work on a client .exe as well, as long as you are referencing System.Web.dll and using System.Web.Configuration namespace.

This way of accessing the configuration is called Configuration Runtime API. It’s faster and simpler. It uses the static GetSection() method.

However, if you need to open a specific configuration on a client .exe you'll need ConfigurationManager.OpenExeConfiguration() which will return a Configuration object instance. This way of accessing the configuration is called Configuration Design API. It's more powerful and flexible.

In synthesis, accessing design web configuration will require WebConfigurationManager and accessing design desktop configuration will require ConfigurationManager. For runtime configuration you can use either object. I'll use ConfigurationManager though. It has three letter less to type and, by default, it doesn't require the <%@ Import %> directive on web pages.

There will be no penalty with loss of (read-only) functionality?

Note that some configuration sections can choose to be hidden on runtime, usually for security reasons, so not all sections are available. Opening design configuration requires High trust on web applications.

If you run the following code in a .aspx page, you'll see the differences on Runtime and Design for all sections on the web app.

void Page_Load() {
Configuration cfg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
PrintSections( cfg.Sections);
PrintGroups( cfg.SectionGroups );
}

void PrintSections(ConfigurationSectionCollection sections) { 
   foreach(ConfigurationSection section in sections) {
      Response.Write(section.SectionInformation.SectionName + "<br />");
      Response.Write("Design: [" + section + "]<br />");
      object o = ConfigurationManager.GetSection(section.SectionInformation.SectionName);
      if ( o == null ) {
         Response.Write("Runtime: [null]<br />");
      }
      else {
         Response.Write("Runtime: [" + o.GetType().ToString() + "]<br />");
      }
   }
}

void PrintGroups(ConfigurationSectionGroupCollection groups) {
   foreach (ConfigurationSectionGroup group in groups) {
         PrintSections(group.Sections);
   }
 }


Also, any word on why the functionality was split into the two, completely independent managers?

I guess that at some point they grew so big that need to be split on two. The generic configuration is big enough (It requires its own assembly System.Configuration.dll). But I think you are right. They could have shared a common ancestor.

一個蔔蔔一個坑!