我花了几个小时试图确定导致我的自定义配置部分失败的原因,但我似乎无法找到问题的根源。
我收到错误:
类型' System.Configuration.ConfigurationErrorsException'的异常发生在System.Configuration.dll中但未在用户代码中处理
附加信息:属性' 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
答案 0 :(得分:0)
试试这个
<configSections>
<section name="tankConfiguration" type="TankInventory.Configurations.TankConfigurationSection"
allowLocation="true"
allowDefinition="Everywhere"
/>
<tankConfiguration afServer ="Test123" afDatabase ="Test123" tankTemplate ="Test21345"/>>