c# - 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>
解决方案
验证configSections
web.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;
}
}
推荐阅读
- java - 文本在屏幕上不断滚动
- javascript - 尝试使用 reduce 对数组中对象的属性求和:未定义?
- python - 从另一个 docker 容器连接到 docker 容器中的 mysql 服务器
- flutter - 没有为静态变量定义 getter,也没有为类中声明的方法定义 getter
- python - Pyspark:使用 Python 从 Spark 2.4 连接到 MS SQL Server 2017 时没有合适的驱动程序错误
- c++ - Visual Studio 2017 15.9.13 不能使用自动 C++ 模板
- windows - 使用 ConvertTo-SecureString 问题:我可以使用 powershell 重置多个 ADUC 密码吗?
- javascript - 啁啾 wasm DOMException
- nosql - 使用 Fakeit 生成数据
- node.js - 未经同意屏幕使用 Drive API 将文件上传到 Google Drive