Asp.net

無法辨識的配置部分

  • September 8, 2020

我創建了一個自定義配置部分,如下所示

<configSections>
</configSections>
<Tabs>
   <Tab name="Dashboard" visibility="true" />
   <Tab name="VirtualMachineRequest" visibility="true" />
   <Tab name="SoftwareRequest" visibility="true" />
</Tabs>

自定義配置部分處理程序

namespace EDaaS.Web.Helper
{
   public class CustomConfigurationHandler : ConfigurationSection
   {
       [ConfigurationProperty("visibility", DefaultValue = "true", IsRequired = false)]
       public Boolean Visibility
       {
           get
           {
               return (Boolean)this["visibility"];
           }
           set
           {
               this["visibility"] = value;
           }
       }
   }
}

執行應用程序時拋出異常 Unrecognized configuration section Tabs。如何解決這個問題?

您需要編寫一個configuration handler來解析這個自定義部分。然後在您的配置文件中註冊此自定義處理程序:

<configSections>
   <section name="mySection" type="MyNamespace.MySection, MyAssembly" />
</configSections>

<mySection>
   <Tabs>
       <Tab name="one" visibility="true"/>
       <Tab name="two" visibility="true"/>
   </Tabs>
</mySection>

現在讓我們定義相應的配置部分:

public class MySection : ConfigurationSection
{
   [ConfigurationProperty("Tabs", Options = ConfigurationPropertyOptions.IsRequired)]
   public TabsCollection Tabs
   {
       get
       {
           return (TabsCollection)this["Tabs"];
       }
   }
}

[ConfigurationCollection(typeof(TabElement), AddItemName = "Tab")]
public class TabsCollection : ConfigurationElementCollection
{
   protected override ConfigurationElement CreateNewElement()
   {
       return new TabElement();
   }

   protected override object GetElementKey(ConfigurationElement element)
   {
       if (element == null)
       {
           throw new ArgumentNullException("element");
       }
       return ((TabElement)element).Name;
   }
}

public class TabElement : ConfigurationElement
{
   [ConfigurationProperty("name", IsRequired = true, IsKey = true)]
   public string Name
   {
       get { return (string)base["name"]; }
   }

   [ConfigurationProperty("visibility")]
   public bool Visibility
   {
       get { return (bool)base["visibility"]; }
   }
}

現在您可以訪問設置:

var mySection = (MySection)ConfigurationManager.GetSection("mySection");

引用自:https://stackoverflow.com/questions/13985914