0

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

我得到一个错误:

An exception of type 'System.Configuration.ConfigurationErrorsException' occurred in System.Configuration.dll but was not handled in user code

Additional information: The value for the property 'afDatabase' is not valid. The error is: The string must be at least 1 characters long.

看着我的配置部分,我开始通过注意到我有一个字符串验证器设置:

配置CS

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

    [ConfigurationProperty("afDatabase", IsRequired = true)] 
    [StringValidator(InvalidCharacters = "[email protected]#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)] 
    public String AfDatabase 
    { 
     get 
     { 
      return (String)this["afDatabase"]; 
     } 
     set 
     { 
      this["afDatabase"] = value; 
     } 
    } 
    [ConfigurationProperty("tankTemplate", IsRequired = true)] 
    [StringValidator(InvalidCharacters = "[email protected]#$%^&*()[]{}/;'\"|\\", 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

+0

在这一步,你得到了一个错误?试图获得价值,或者只是在运行时?......别的东西? –

+0

在运行时 - 每当我运行应用程序时发生。 – user44036

回答

0

试试这个

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

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