Custom ConfigurationSection: CallbackValidator with an empty string

I am writing a custom configuration section, and I would like to check the configuration property with a callback, as in this example:

using System; using System.Configuration; class CustomSection : ConfigurationSection { [ConfigurationProperty("stringValue", IsRequired = false)] [CallbackValidator(Type = typeof(CustomSection), CallbackMethodName = "ValidateString")] public string StringValue { get { return (string)this["stringValue"]; } set { this["stringValue"] = value; } } public static void ValidateString(object value) { if (string.IsNullOrEmpty((string)value)) { throw new ArgumentException("string must not be empty."); } } } class Program { static void Main(string[] args) { CustomSection cfg = (CustomSection)ConfigurationManager.GetSection("customSection"); Console.WriteLine(cfg.StringValue); } } 

And my App.config file looks like this:

 <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="customSection" type="CustomSection, config-section"/> </configSections> <customSection stringValue="lorem ipsum"/> </configuration> 

My problem is that when the ValidateString function is called, the value parameter is always an empty string, and therefore the check is not performed. If I just delete the validator, the string value will be correctly initialized with the value in the configuration file.

What am I missing?

EDIT . I found that in fact the verification function is called twice: the first time with the default value of the property, which is an empty string if nothing is specified, the second time with the real value read from the configuration file. Is there any way to change this behavior?

+4
source share
1 answer

I had the same problem (except that I created a special validator instead of using CallbackValidator) - the validator was called twice, the first call being transmitted by default, and the second in the configured values. Since an empty string was not a valid value for one of my properties, it caused a configuration error even when I configured the string value.

So, I just changed the validator to return an empty string, rather than checking it. You can then use the IsRequired attribute to control what happens when a value is not provided.

+2
source

Source: https://habr.com/ru/post/1308990/


All Articles