Why does StringValidator always fail for custom configuration section?

后端 未结 4 1635
一整个雨季
一整个雨季 2021-02-19 09:41

I have created a custom configuration section in a c# class library by inheriting from ConfigurationSection. I reference the class library in my web application (a

4条回答
  •  伪装坚强ぢ
    2021-02-19 10:24

    I had this problem for a while, then I realized that the validators are not for making attribute or elements required, they are for validating them.

    To make a property required you need to use the IsRequired and ConfigrationPropertyOptions.IsRequired, e.g.

    [ConfigurationProperty("casLogoutUrl", DefaultValue = null, IsRequired = true, Options = ConfigurationPropertyOptions.IsRequired)]
    [StringValidator(MinLength=10)]
    

    Or (if using the api)

    ConfigurationProperty casLoginUrl = new ConfigurationProperty("casLoginUrl", typeof(string), null, null, new StringValidator(1), ConfigurationPropertyOptions.IsRequired);
    

    Doing this, the Configuration framework will handle the property being required itself, and the validator handles validating what's in the value. Validators are not meant for making something required.

    This also works on elements to make child elements required. E.g. if you are making a custom ConfigSection with child elements and need a child element to be required. However, if you make a CustomValidator that inherits from ConfigurationValidatorBase, you need to make use of ElementInformation.IsPresent, e.g.

                public override void Validate(object value)
            {
                CredentialConfigurationElement element = (CredentialConfigurationElement)value;
                if (!element.ElementInformation.IsPresent)
                    return; //IsRequired is handle by the framework, don't throw error here  only throw an error if the element is present and it fails validation.
                if (string.IsNullOrEmpty(element.UserName) || string.IsNullOrEmpty(element.Password))
                    throw new ConfigurationErrorsException("The restCredentials element is missing one or more required Attribute: userName or password.");
            }
    

    Long story short, you are missing the options part of your attribute to make it required and shouldn't use StringValidator(MinLength=1) to make it required. In fact StringValidator(MinLength=1) is completely redundant. If you make it required it's impossible for MinLength=1 to fail without the Required failing first because if it's present, it's guaranteed to be at least 1 character long.

    Change your validator to

    [ConfigurationProperty("appCode", IsRequired = true, Options=ConfigurationPropertyOptions.IsRequired)]
    

    Then ditch the string validator.

提交回复
热议问题