App.config - 自定义部分无效

时间:2008-11-20 19:36:37

标签: c#

我最近开始构建一个Web应用程序的控制台版本。我从web.config中复制了自定义部分。到我的app.config。当我去获取配置信息时,我收到此错误:

为x / y创建配置节处理程序时发生错误:无法从程序集'System.Configuration

加载类型'x'

它不喜欢的行是:

将ConfigurationManager.GetSection(“X / Y”)返回为Z;

有人碰到这样的事吗?

我能够添加

<add key="IsReadable" value="0"/> 
在appSettings中

并阅读它。

增加:

我确实已经定义了自定义部分:

  <configSections>
    <sectionGroup name="x">
      <section name="y" type="zzzzz"/>
    </sectionGroup>

  </configSections>

5 个答案:

答案 0 :(得分:3)

听起来你的配置部分处理程序没有定义

<configSection>
    <section
            name="YOUR_CLASS_NAME_HERE"
            type="YOUR.NAMESPACE.CLASSNAME, YOUR.NAMESPACE, Version=1.1.0.0, Culture=neutral, PublicKeyToken=PUBLIC_TOKEN_ID_FROM_ASSEMBLY"
            allowLocation="true"
            allowDefinition="Everywhere"
          />
</configSection>

答案 1 :(得分:3)

我最近遇到了同样的问题。我为Web应用程序创建了一个自定义的sectiongroup(运行得很好),但是当我将这个图层移植到控制台应用程序时,sectiongroup失败了。

关于您的部分定义中需要多少“类型”,您的问题是正确的。我已经使用以下示例修改了您的配置部分:

<configSection>
    <section
        name="yourClassName"
        type="your.namespace.className, your.assembly"
        allowLocation="true"
        allowDefinition="Everywhere" />
</configSection>

您会注意到,该类型现在具有类名,后跟程序集名称。这是在Web环境之外进行交互所必需的。

注意:程序集名称不一定等于您的名称空间(对于给定的部分)。

答案 2 :(得分:0)

如果你想要一个自定义配置处理程序,你必须定义类并引用它,如Steven Lowe所示。您可以继承预定义的处理程序,也可以只使用appSetting部分中提供的值/密钥对。

答案 3 :(得分:0)

在文件的顶部,您需要在部分内部使用configSection标记。

您也可以拥有sectionGroup。例如:

<configuration>
   <configSections>
     <sectionGroup name="x">
       <section name="y" type="a, b"/>
     </sectionGroup>
    <configSections>
</configuration>

答案 4 :(得分:0)

此类可用作任何类型的通用自定义配置节处理程序...

public class XmlConfigurator : IConfigurationSectionHandler
    {
        public object Create(object parent, object configContext, XmlNode section)
        {
            if (section == null) return null;
            Type sectionType = Type.GetType((string)(section.CreateNavigator()).Evaluate("string(@configType)"));
            XmlSerializer xs = new XmlSerializer(sectionType);
            return xs.Deserialize(new XmlNodeReader(section));
        }
    }

在你的app.config中,添加

  <section name="NameofConfigSection"  type="NameSpace.XmlConfigurator, NameSpace.Assembly"/>

在配置节元素中,添加一个属性以指定希望根元素反序列化的类型。

<?xml version="1.0" encoding="utf-8" ?>

<NameofConfigSection configType="NameSpace.NameofTypeToDeserializeInto, Namespace.Assembly" >

 ... 

</NameofConfigSection>
相关问题