System.Configuration.ConfigXmlElement中存在无效的强制转换异常



我正试图使用以下代码访问我的"web.config"文件的一个部分

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

但是得到exeception作为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>

验证web.config中的configSections条目是否为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;
}
}

最新更新