为什么web.config配置节中的属性值有字符限制?

时间:2014-11-10 13:57:39

标签: c# .net xml asp.net-mvc web-config

最近,我遇到了一个异常,声明如下:

Critical Unexpected Error Occured:System.Configuration.ConfigurationErrorsException: The value for the property 'foo' is not valid. The error is: The string must be no more than 999 characters long.

但是,我找不到任何关于此类错误的文档,并且所有内容似乎都表明这些值没有字符限制。

当然,为了解决这个问题,我可以缩短字符串。但这似乎很有趣,它会有这种看似随意的字符限制。

是否有任何与此问题相关的文档来描述发生这种情况的原因,以及字符限制背后的原因?

完整堆栈跟踪如下:

Critical Unexpected Error Occured:System.Configuration.ConfigurationErrorsException: The value for the property 'foo' is not valid. The error is: The string must be no more than 999 characters long. (C:\workspace\foobar\src\Manager\foo\bar.Web\web.config line 34) at System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult) at System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject) at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) at System.Configuration.BaseConfigurationRecord.GetSection(String configKey) at System.Web.HttpContext.GetSection(String sectionName) at System.Web.Configuration.HttpConfigurationSystem.GetSection(String sectionName) at System.Web.Configuration.HttpConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String configKey)

2 个答案:

答案 0 :(得分:0)

为什么你想要一个web配置属性这么长?是否不可能有一个指向xml文件的应用程序设置,您可以在其中手动构造每个元素,反序列化为对象并从中读取?

答案 1 :(得分:0)

StringValidatorAttribute可以在给定属性中施加最小或最大长度。

使用该属性访问ConfigurationSection对象的示例。添加超过60的字符串将引发您指定的相同错误:

[ConfigurationProperty("fileName", DefaultValue = "default.txt",
    IsRequired = true, IsKey = false)]
[StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
    MinLength = 1, MaxLength = 60)]
public string FileName
{
    get
    {
        return (string)this["fileName"];
    }
    set
    {
        this["fileName"] = value;
    }
}

参考:https://msdn.microsoft.com/en-us/library/system.configuration.stringvalidatorattribute(v=vs.110).aspx