我花了幾個小時試圖確定是什麼導致我的自定義配置節失敗,但我似乎無法找到問題的根源。配置節設置不初始化
我得到一個錯誤:
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
在這一步,你得到了一個錯誤?試圖獲得價值,或者只是在運行時?......別的東西? –
在運行時 - 每當我運行應用程序時發生。 – user44036