是否可以在自定义配置部分中使用任意XML?

Jas*_*son 9 .net asp.net

假设我在ASP.NET web.config中定义了一个配置部分,如:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="system.web">
      <section name="MySettings" type="MyCompany.MyProject.Configuration.MySettings" allowLocation="true" allowDefinition="Everywhere" restartOnExternalChanges="false" />
    </sectionGroup>
  </configSections>
  <system.web>
    <MySettings knownProperty="some_value" unknownProperty="other_value" />
  </system.web>
</configuration>
Run Code Online (Sandbox Code Playgroud)

假设我MySettings : System.Configuration.ConfigurationSection 没有 定义unknownProperty:

using System.Configuration;

namespace MyCompany.MyProject.Configuration
{
    public class MySettings : ConfigurationSection
    {
      public MySettings() { }

      [ConfigurationProperty("knownProperty", DefaultValue="default_value")]
      public string KnownProperty
      {
        get { return (string)this["knownProperty"]; }
      }

      // I'm not defining unknownProperty here on purpose
    }
}
Run Code Online (Sandbox Code Playgroud)

无论如何运行应用程序而没有得到配置错误抱怨无法识别的属性'unknownProperty'?

另外,我可以通过一种方法来捕获该错误并忽略它,如果可能的话.

换句话说,我希望XML具有未在其绑定的匹配类型中定义的属性.可以在现有Configuration API的范围内完成吗?

Dan*_*iel 7

我很确定它是可能的,因为一些内置的部分,如WCF和成员资格,这样做没有错误.OnDeserializeUnrecognizedAttribute是否满足您的需求?

protected override bool OnDeserializeUnrecognizedAttribute(string name, string value){
//don't call base to avoid error
}
Run Code Online (Sandbox Code Playgroud)