0

我花了几个小时试图确定是什么导致我的自定义配置部分失败,但我似乎无法找到问题的根源。

我收到一个错误:

System.Configuration.dll 中出现“System.Configuration.ConfigurationErrorsException”类型的异常,但未在用户代码中处理

附加信息:属性“afDatabase”的值无效。错误是:字符串必须至少有 1 个字符长。

查看我的配置部分,我首先注意到我设置了一个字符串验证器:

配置 CS

public class TankConfigurationSection : ConfigurationSection
{
    [ConfigurationProperty("afServer", IsRequired = true)]
    [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 0, MaxLength = 60)]
    public String AfServer
    {
        get
        {
            return (String)this["afServer"];
        }
        set
        {
            this["afServer"] = value;
        }
    }

    [ConfigurationProperty("afDatabase",  IsRequired = true)]
    [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
    public String AfDatabase
    {
        get
        {
            return (String)this["afDatabase"];
        }
        set
        {
            this["afDatabase"] = value;
        }
    }
    [ConfigurationProperty("tankTemplate", IsRequired = true)]
    [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
    public String TankTemplate
    {
        get
        {
            return (String)this["tankTemplate"];
        }
        set
        {
            this["tankTemplate"] = value;
        }
    }

}

我删除了 afServer 上 1 个字符长度的字符串验证器要求,并注意到错误发生在 afDatabase 上。在我看来,这些值从未被初始化,这就是为什么当 afServer 的最小长度为 1 时,它会失败,但是通过删除它,错误会落在 afDatabase 上。

这是我的 web.config

    <configuration>

   <!-- Configuration section-handler declaration area. -->
  <configSections>
    <sectionGroup name="tankConfigurationGroup">
      <section 
        name="tankConfiguration" 
        type="TankInventory.Configurations.TankConfigurationSection"
        allowLocation="true" 
        allowDefinition="Everywhere"
      />
    </sectionGroup>
      <!-- Other <section> and <sectionGroup> elements. -->
  </configSections>

  <!-- Configuration section settings area. -->
<tankConfigurationGroup>
          <tankConfiguration afServer ="Test123" afDatabase ="Test123" tankTemplate ="Test21345" >
        </tankConfiguration>
      </tankConfigurationGroup>
</configuration>

我一直以此为指导: https ://msdn.microsoft.com/en-us/library/2tw134k3.aspx

4

1 回答 1

0

尝试这个

<configSections>    
  <section name="tankConfiguration" type="TankInventory.Configurations.TankConfigurationSection"
    allowLocation="true" 
    allowDefinition="Everywhere"
  />

      <tankConfiguration afServer ="Test123" afDatabase ="Test123" tankTemplate ="Test21345"/>>

于 2016-07-25T20:06:56.770 回答