创建配置节处理程序时发生错误

Joh*_*oDo 4 c# asp.net web-config unity-container c#-4.0

我有一个dot.NET 4.0 Web应用程序,其中定义了自定义部分:

<configuration>
    <configSections>
    <section name="registrations" type="System.Configuration.IgnoreSectionHandler, System.Configuration, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="true" restartOnExternalChanges="true" allowLocation="true"/>
    ....
Run Code Online (Sandbox Code Playgroud)

在web.config文件的末尾我有相应的部分:

  ....
  <registrations>
    .....
  </registrations>
</configuration>
Run Code Online (Sandbox Code Playgroud)

我每次打电话System.Configuration.ConfigurationManager.GetSection("registrations");都会得到以下异常:

为注册创建配置节处理程序时发生错误:给定的程序集名称或代码库无效.(来自HRESULT的异常:0x80131047)(C:\ ...\web.config第13行)

我也在使用Unity,但不知道这是否与错误有关.

你以前遇到过这个错误吗?我该如何解决?我是否需要更换IgnoreSectionHandler其他东西?

Dou*_*son 9

鉴于此app.config:

<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="registrations" type="MyApp.MyConfigurationSection, MyApp" />
    </configSections>
    <registrations myValue="Hello World" />
</configuration>
Run Code Online (Sandbox Code Playgroud)

然后尝试使用:

namespace MyApp
{
    class Program
    {
        static void Main(string[] args) {
            var config = ConfigurationManager.GetSection(MyConfigurationSection.SectionName) as MyConfigurationSection ?? new MyConfigurationSection();

            Console.WriteLine(config.MyValue);

            Console.ReadLine();
        }
    }

    public class MyConfigurationSection : ConfigurationSection
    {
        public const String SectionName = "registrations";

        [ConfigurationProperty("myValue")]
        public String MyValue {
            get { return (String)this["myValue"]; }
            set { this["myValue"] = value; }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我在部分名称(<section name ="registrations"type ="MyApp.MyConfigurationSection,MyApp"/>)声明中缺少名称空间",MyApp".干杯! (4认同)

Sha*_*ood 7

您缺少App.Config中部分的type属性中的命名空间.事实上,你也不需要完整的装配信息.只有命名空间就足够了

更新1

  yourcustomconfigclass config =(yourcustomconfigclass)System.Configuration.ConfigurationManager.GetSection(
    "registrations");
Run Code Online (Sandbox Code Playgroud)

并在配置文件中只写

   <section name="registrations" type="System.Configuration.IgnoreSectionHandler" requirePermission="true" restartOnExternalChanges="true" allowLocation="true"/>
Run Code Online (Sandbox Code Playgroud)