【问题标题】:What's the difference between the WebConfigurationManager and the ConfigurationManager?WebConfigurationManager 和 ConfigurationManager 有什么区别?
【发布时间】:2010-10-16 10:30:09
【问题描述】:

WebConfigurationManagerConfigurationManager 有什么区别?

我应该什么时候使用一个而不是另一个?

更新

我刚刚查看了WebConfigurationManager,由于某种原因,您无法像在ConfigurationManager 中那样访问连接字符串(就像一个数组)。谁能告诉我为什么MS会这样?使用WebConfigurationManager 获取所需的连接字符串似乎很痛苦。

再次更新警告!

如果您没有在项目中添加对 System.Configuration 命名空间的引用,那么当您尝试访问 WebConfigurationManager.ConnectionStrings 时,Visual Studio 将显示错误!

【问题讨论】:

  • 我认为“警告”不是很准确。我使用 system.web.configuration 连接字符串而不需要 system.configuration

标签: c# .net asp.net configurationmanager webconfigurationmanager


【解决方案1】:

WebConfigurationManger 知道如何处理 Web 应用程序中的配置继承。如您所知,一个应用程序中可能有多个 web.config 文件——一个在站点的根目录中,而在子目录中则为任意数量。您可以将路径传递给 GetSection() 方法以获取可能的覆盖配置。

如果我们用 Reflector 查看 WebConfigurationManager,那么事情就很清楚了:

public static object GetSection(string sectionName)
{
    ...
    return ConfigurationManager.GetSection(sectionName);
}

public static object GetSection(string sectionName, string path)
{
    ...
    return HttpConfigurationSystem.GetSection(sectionName, path);
}

【讨论】:

    【解决方案2】:

    虽然 WebConfigurationManager 位于 System.Web 程序集中,但它返回的 ConnectionStringSettingsCollection 位于 System.Configuration。

    如果遇到错误

    无法将 [] 索引应用于类型表达式 'System.Configuration.ConnectionStringSettingsCollection'

    尝试访问数组索引时...

    WebConfigurationManager.ConnectionStrings["Name"].ConnectionString
    

    确保您引用了程序集 System.Configuration

    【讨论】:

      【解决方案3】:

      不确定您对连接字符串的含义。

      调用WebConfigurationManager.ConnectionStrings 会返回一个System.Configuration.ConnectionStringSettingsCollection,这与调用ConfigurationManager.ConnectionStrings 时得到的结果相同。

      否则,正如 XOR 所说,它旨在处理多个分层 web.config,当您在应用程序中移动文件夹时根据需要将它们组合起来。

      【讨论】:

        【解决方案4】:

        WebConfigurationManager 专为 ASP.NET 应用程序而设计。

        WebConfigurationManager 提供了额外的方法来加载适用于 Web 应用程序的配置文件。

        ConfigurationManager 还提供了加载适用于“.exe”应用程序的配置文件的方法。

        我建议看一下 WebConfigurationManager,看看它是否为您提供了您无法使用 ConfigurationManager 做的任何事情并改用它,否则使用 ConfigurationManager 将使您的代码在 Web 和桌面之间无缝使用变得容易得多aps。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-09-04
          • 2011-10-18
          • 2010-10-02
          • 2011-12-12
          • 2010-09-16
          • 2012-03-14
          • 2012-02-06
          • 2011-02-25
          相关资源
          最近更新 更多