【问题标题】:How to open a config file app settings using ConfigurationManager?如何使用 ConfigurationManager 打开配置文件应用程序设置?
【发布时间】:2011-12-10 18:55:58
【问题描述】:

我的配置文件位于这里:

"~/Admin/Web.config"

我尝试通过以下代码打开它,但没有成功:

var physicalFilePath = HttpContext.Current.Server.MapPath("~/Admin/Web.config");
var configMap = new ConfigurationFileMap(physicalFilePath);
var configuration = ConfigurationManager.OpenMappedMachineConfiguration(configMap);
var appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");

当 appsettings 行运行时,它会抛出以下错误消息:

Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.

我的 Web.Config 如下所示:

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <appSettings>
    <add key="AdminUsername" value="Test1"/>
    <add key="AdminPassword" value="Test2"/>
  </appSettings>
  <connectionStrings></connectionStrings>
</configuration>

如何获取应用设置?

【问题讨论】:

    标签: c# asp.net web-config configurationmanager


    【解决方案1】:

    如果您正在寻找向 Web.config 添加一些内容,然后从代码中读取它。 您需要的是 Web.config 中的自定义配置部分

    看这里: How do I define custom web.config sections with potential child elements and attributes for the properties? 和这里: Creating Custom Configuration Sections in Web.config - 4GuysFromRolla.com

    【讨论】:

      【解决方案2】:

      对于web-app,你需要使用System.Web.Configuration.WebConfigurationManager类,不需要设置绝对路径。

      var web=System.Web.Configuration.WebConfigurationManager
                .OpenWebConfiguration("~/admin/web.config");
      
      String appValue=web.AppSettings.Settings["key"].Value;
      

      【讨论】:

      • 访问其 AppSettings 属性时出现此错误:无法将“System.Configuration.DefaultSection”类型的对象转换为“System.Configuration.AppSettingsSection”类型。
      • 如何打开.net core appsettings.json?
      猜你喜欢
      • 2013-10-16
      • 2010-11-14
      • 2010-09-07
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 2015-09-21
      相关资源
      最近更新 更多