ConfigurationSection - сбой StringValidator

Я хочу сохранить три значения в моем файле ASP.NET web.config в пользовательском элементе, так что это мой web.config:

<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="mySection" type="Foobar.MySection,Foobar" />
    </configSections>

    <mySection baseUri="https://blargh" sid="123" key="abc" />

    <!-- etc, including <system.web> configuration -->
</configuration>

Это мой код конфигурации:

namespace Foobar {

public class MySection : ConfigurationSection {

    public MySection () {
    }

    [ConfigurationProperty("baseUri", IsRequired=true)]
    [StringValidator(MinLength=1)]
    public String BaseUri {
        get { return (String)this["baseUri"]; }
        set { this["baseUri"] = value; }
    }

    [ConfigurationProperty("sid", IsRequired=true)]
    [StringValidator(MinLength=1)]
    public String Sid {
        get { return (String)this["sid"]; }
        set { this["sid"] = value; }
    }

    [ConfigurationProperty("key", IsRequired=true)]
    [StringValidator(MinLength=1)]
    public String Key {
        get { return (String)this["key"]; }
        set { this["key"] = value; }
    }
}
}

И я загружаю его, используя этот код:

MySection section = ConfigurationManager.GetSection("mySection") as MySection;
String x = section.BaseUri;

Однако когда я запускаю свой код в ASP.NET, я получаю это исключение:

[ArgumentException: The string must be at least 1 characters long.]
System.Configuration.StringValidator.Validate(Object value) +679298
System.Configuration.ConfigurationProperty.Validate(Object value) +41

[ConfigurationErrorsException: The value for the property 'baseUri' is not valid. The error is: The string must be at least 1 characters long.]
System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line) +278
System.Configuration.BaseConfigurationRecord.CreateSectionDefault(String configKey, Boolean getRuntimeObject, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object& result, Object& resultRuntimeObject) +59
System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) +1431
System.Configuration.BaseConfigurationRecord.GetSection(String configKey, Boolean getLkg, Boolean checkPermission) +56
System.Configuration.BaseConfigurationRecord.GetSection(String configKey) +8
System.Web.HttpContext.GetSection(String sectionName) +47
System.Web.Configuration.HttpConfigurationSystem.GetSection(String sectionName) +39
System.Web.Configuration.HttpConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String configKey) +6
System.Configuration.ConfigurationManager.GetSection(String sectionName) +78
<my code that calls GetSection>

Почему происходит сбой StringValidator, если в моем файле web.config задано правильно отформатированное значение? Что я пропускаю?

3 ответа

Решение

Так как StringValidator является причиной исключений, которые я сделал в Google, и, по-видимому, это ошибка в.NET Framework: наличие StringValidator с аргументом Minimum Length означает, что он всегда будет отклонять пустую строку "" значение свойства по умолчанию, которое будет установлено фреймворком.

Есть обходные пути, но я не мог оправдать тратить на них время, поэтому я убрал StringValidator атрибуты и мой код теперь работает нормально.

Вот QA, который я нашел: Почему StringValidator всегда терпит неудачу для секции пользовательской конфигурации?

it clearly states that

The value for the property 'baseUri' is not valid

Я думаю, что это должно быть

<mySection baseUri="https://blargh"  sid="123" key="abc" />

StringValidator - это корневая проблема, она может быть решена любым из:

  • Удаление аргумента MinLength
  • Установка MinLength = 0
  • удаление атрибута StringValidator
  • добавление DefaultValue в атрибут ConfigurationProperty

Идеальное определение для свойства выглядит так:

    [ConfigurationProperty("title", IsRequired = true, DefaultValue = "something")]
    [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;’\"|\\"
      , MinLength = 1
      , MaxLength = 256)]
    public string Title
    {
        get { return this["title"] as string; }
        set { this["title"] = value; }
    }
Другие вопросы по тегам