首页 > 解决方案 > System.Configuration.ConfigXmlElement 中的无效转换异常

问题描述

我正在尝试使用以下代码访问我的“web.config”文件的一部分

public static string XMLCheck
    {
        get
        {
            var section = (Hashtable)ConfigurationManager.GetSection("Default.Framework");
            return (string)section["ConnectionString"];
        }
    }

但得到执行作为Unable to cast object of type 'System.Configuration.ConfigXmlElement' to type 'System.Collections.Hashtable' 这里有什么问题?如何纠正?

更新

 <Resources>
      <Resource Uri="resource:Default:CrossDomain" Version="1.0" Id="8ae96c54" IsEnabled="True" Handler="handler:Default:Framework:Resources:Data:Oracle">
        <Properties>
          <Property Name="ConnectionString" Value="Data Source=TESTDB;User Id=TESTUSR;password=TESTPWD;Persist Security Info=false"/>
        </Properties>
      </Resource>
 </Resources>

标签: c#.nethashtableconfig

解决方案


验证configSectionsweb.config 中的条目是否为DictionarySectionHandler

<configuration>
 <configSections>
  <section name="Default.Framework" type="System.Configuration.DictionarySectionHandler" />
 </configSections>
<configuration>

从您更新的代码来看,您似乎正在使用为其配置部分定义自定义 XML 结构的库或框架。通常,您将依赖此库通过其属性公开配置设置。如果你真的想解析 XML,你可以像下面这样使用 XPath:

public static string XMLCheck
{
    get
    {
        var section = (XmlElement)ConfigurationManager.GetSection("Default.Framework");
        var connectionString = section.SelectSingleNode(@"
            descendant::Resource[@Uri='resource:Default:CrossDomain']
            /Properties
            /Property[@Name='ConnectionString']
            /@Value");
        return connectionString.Value;
    }
}

推荐阅读