【问题标题】:Invalid cast exception in System.Configuration.ConfigXmlElementSystem.Configuration.Config Xml 元素中的无效转换异常
【发布时间】:2019-01-05 05:37:09
【问题描述】:

我正在尝试使用以下代码访问我的“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# .net hashtable config


    【解决方案1】:

    确认您的 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;
        }
    }
    

    【讨论】:

    • 它的type="Default.Framework.Configuration.XmlConfigurationSectionHandler..什么需要更新?谢谢
    • 如果您的&lt;Default.Framework&gt; 只是名称-值对的集合,那么更改类型应该是安全的。如果是自定义 XML 结构,则需要将其作为 ConfigXmlElement 实例获取并将其解析为 XML(例如使用 XPath)。
    • 谢谢。请问我的共享代码中需要更新什么?
    • 你能粘贴你的&lt;Default.Framework&gt;元素吗?您可以编辑这些值;我们只需要看看结构
    • 您能建议一下吗?我已经更新了我帖子中的代码..谢谢
    猜你喜欢
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多