在Web.config或App.config中的添加自定義配置 <轉>

来源:http://www.cnblogs.com/Tanghongchang/archive/2017/07/17/7196118.html
-Advertisement-
Play Games

.Net中的System.Configuration命名空間為我們在web.config或者app.config中自定義配置提供了完美的支持。最近看到一些項目中還在自定義xml文件做程式的配置,所以忍不住寫一篇用系統自定義配置的隨筆了。 如果你已經對自定義配置瞭如指掌,請忽略這篇文章。 言歸正傳, ...


   

.Net中的System.Configuration命名空間為我們在web.config或者app.config中自定義配置提供了完美的支持。最近看到一些項目中還在自定義xml文件做程式的配置,所以忍不住寫一篇用系統自定義配置的隨筆了。

如果你已經對自定義配置瞭如指掌,請忽略這篇文章。

言歸正傳,我們先來看一個最簡單的自定義配置

<?xml version="1.0" encoding="utf-8" ?> <configuration>   <configSections>     <section name="simple" type="ConfigExample.Configuration.SimpleSection,ConfigExample"/>   </configSections>   <simple maxValue="20" minValue="1"></simple> </configuration>

在配置文件中使用自定義配置,需要在configSections中添加一個section元素,並制定此section元素對應的類型和名字。然後再在configuration根節點下麵添加此自定義配置,如上例中的simple節點。simple節點只有兩個整形數的屬性maxValue和minValue。

要在程式中使用自定義配置我們還需要實現存取這個配置塊的類型,一般需要做如下三件事:
1. 定義類型從System.Configuration.ConfigurationSection繼承
2. 定義配置類的屬性,這些屬性需要用ConfigurationProperty特性修飾,並制定屬性在配置節中的名稱和其他一些限制信息
3. 通過基類的string索引器實現屬性的get ,set

非常簡單和自然,如下是上面配置類的實現:

public class SimpleSection:System.Configuration.ConfigurationSection {     [ConfigurationProperty("maxValue",IsRequired=false,DefaultValue=Int32.MaxValue)]     public int MaxValue     {         get         {             return  (int)base["maxValue"];         }         set         {             base["maxValue"] = value;         }     }       [ConfigurationProperty("minValue",IsRequired=false,DefaultValue=1)]     public int MinValue     {         get { return (int) base["minValue"];}         set { base["minValue"] = value; }     }         [ConfigurationProperty("enabled",IsRequired=false,DefaultValue=true)]     public bool Enable     {         get         {             return (bool)base["enabled"];         }         set         {             base["enabled"] = value;         }     } }

這樣子一個簡單的配置類就完成了,怎麼在程式中使用這個配置呢?需要使用ConfigurationManager類(要引用System.configuration.dll這個dll只有在.Net2.0之後的版本中才有)的GetSection方法獲得配置就可以了。如下代碼:

SimpleSection simple = ConfigurationManager.GetSection("simple") as SimpleSection; Console.WriteLine("simple minValue={0} maxValue = {1}",simple.MinValue,simple.MaxValue);

這個配置類太過簡陋了,可能有時候我們還需要更複雜的構造,比如在配置類中使用類表示一組數據,下麵我們看一個稍微複雜一點的自定義配置

<?xml version="1.0" encoding="utf-8" ?> <configuration>   <configSections>     <section name="complex" type="ConfigExample.Configuration.ComplexSection,ConfigExample"/>   </configSections>   <complex height="190">     <child firstName="James" lastName="Bond"/>   </complex> </configuration>

這個配置的名字是complex,他有一個屬性height,他的節點內還有一個child元素這個元素有兩個屬性firstName和lastName;對於這個內嵌的節點該如何實現呢?首先我們需要定義一個類,要從ConfigurationElement類繼承,然後再用和SimpleSection類似的方法定義一些用ConfigurationProperty特性修飾的屬性就可以了,當然屬性值的get,set也要使用基類的索引器。如下實現:

public class ComplexSection : ConfigurationSection {     [ConfigurationProperty("height", IsRequired = true)]     public int Height     {         get         {             return (int)base["height"];         }         set         {             base["height"] = value;         }     }       [ConfigurationProperty("child", IsDefaultCollection = false)]     public ChildSection Child     {         get         {             return (ChildSection)base["child"];         }         set         {             base["child"] = value;         }     } }   public class ChildSection : ConfigurationElement {     [ConfigurationProperty("firstName", IsRequired = true, IsKey = true)]     public string FirstName     {         get         {             return (string)base["firstName"];         }         set         {             base["firstName"] = value;         }     }       [ConfigurationProperty("lastName", IsRequired = true)]     public string LastName     {         get         {             return (string)base["lastName"];         }         set         {             base["lastName"] = value;         }     } }

還有稍微再複雜一點的情況,我們可能要在配置中配置一組相同類型的節點,也就是一組節點的集合。如下麵的配置:

<?xml version="1.0" encoding="utf-8" ?> <configuration>   <configSections>     <section name="complex" type="ConfigExample.Configuration.ComplexSection,ConfigExample"/>   </configSections>   <complex height="190">     <child firstName="James" lastName="Bond"/>       <children>       <add firstName="Zhao" lastName="yukai"/>       <add firstName="Lee" lastName="yukai"/>       <remove firstName="Zhao"/>     </children>   </complex> </configuration>

請看children節點,它就是一個集合類,在它裡面定義了一組add元素,也可以有remove節點把已經添進去的配置去掉。

要使用自定義節點集合需要從ConfigurationElementCollection類繼承一個自定義類,然後要實現此類GetElementKey(ConfigurationElement element)和ConfigurationElement CreateNewElement()兩個方法;為了方便的訪問子節點可以在這個類裡面定義只讀的索引器。請看下麵的實現

public class Children : ConfigurationElementCollection {     protected override object GetElementKey(ConfigurationElement element)     {         return ((ChildSection)element).FirstName;     }       protected override ConfigurationElement CreateNewElement()     {         return new ChildSection();     }       public ChildSection this[int i]     {         get         {             return (ChildSection)base.BaseGet(i);         }     }       public ChildSection this[string key]     {         get         {             return (ChildSection)base.BaseGet(key);         }     }   }

當然要使用此集合類我們必須在Complex類中添加一個此集合類的屬性,並要指定集合類的元素類型等屬性,如下:

[ConfigurationProperty("children", IsDefaultCollection = false)]     [ConfigurationCollection(typeof(ChildSection), CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap, RemoveItemName = "remove")]     public Children Children     {         get         {             return (Children)base["children"];         }         set         {             base["children"] = value;         } }

我們會經常用到類似appSettings配置節的鍵值對的構造,這時候我們就不必再自己實現了,我們可以直接使用現有的System.Configuration.NameValueConfigurationCollection類來定義一個自定義的鍵值對。可以在Complex類中定義如下屬性

[ConfigurationProperty("NVs", IsDefaultCollection = false)]     public System.Configuration.NameValueConfigurationCollection NVs     {         get         {             return (NameValueConfigurationCollection)base["NVs"];         }         set         {             base["NVs"] = value;         } }

然後在配置文件的complex節中添加鍵值對配置

<NVs>     <add name="abc" value="123"/>     <add name="abcd" value="12d3"/> </NVs>

到這兒已經基本上可以滿足所有的配置需求了。不過還有一點更大但是不複雜的概念,就是sectionGroup。我們可以自定義SectionGroup,然後在sectionGroup中配置多個section;分組對於大的應用程式是很有意義的。

如下配置,配置了一個包含simple和一個complex兩個section的sectionGroup

<?xml version="1.0" encoding="utf-8" ?> <configuration>   <configSections>     <sectionGroup type="ConfigExample.Configuration.SampleSectionGroup,ConfigExample" name="sampleGroup">       <section type="ConfigExample.Configuration.SimpleSection,ConfigExample" allowDefinition="Everywhere" name="simple" />       <section type="ConfigExample.Configuration.ComplexSection,ConfigExample" allowDefinition="Everywhere" name="complex"/>     </sectionGroup>   </configSections>   <sampleGroup>     <simple maxValue="20" minValue="1">     </simple>       <complex height="190">       <child firstName="James" lastName="Bond"/>       <children>         <add firstName="Zhao" lastName="yukai"/>         <add firstName="Lee" lastName="yukai"/>         <remove firstName="Zhao"/>       </children>   <NVs>     <add name="abc" value="123"/>     <add name="abcd" value="12d3"/>   </NVs>     </complex>   </sampleGroup> </configuration>

為了方便的存取sectionGroup中的section我們可以實現一個繼承自System.Configuration.ConfigurationSectionGroup類的自定義類。實現很簡單,就是通過基類的Sections[“sectionName”]索引器返回Section。如下:

public class SampleSectionGroup : System.Configuration.ConfigurationSectionGroup {     public SimpleSection Simple     {         get         {             return (SimpleSection)base.Sections["simple"];         }     }       public ComplexSection Complex     {         get         {             return (ComplexSection)base.Sections["complex"];         }     } }

需要註意的是SectionGroup不能使用ConfigurationManager.GetSection(string)方法來獲得,要獲得sectionGroup必須通過Configuration類的SectionGroups[string]索引器獲得,如下示例代碼:

SampleSectionGroup sample = (SampleSectionGroup)ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).SectionGroups["sampleGroup"];

總結:

.Net framework給我們提供了一套很方便的配置庫,我們只需要繼承對應的類簡單的配置一下就可以方便的使用在web.config或者app.config中配置的自定義節點了。

 

轉自 http://www.cnblogs.com/yukaizhao/archive/2011/12/02/net-web-config-costom-config-implement.html

       
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ASP.NET Core 輕量化開源論壇項目,ASP.NET Core Light forum NETCoreBBS 採用 ASP.NET Core + EF Core Sqlite + Bootstrap 開發。 GitHub: https://github.com/linezero/NETCor ...
  • 開頭添加變數: Point mouseOff;//滑鼠移動位置變數 bool leftFlag;//標簽是否為左鍵 事件部分: ps:很常用的幾串字元。 記住! 記住! 記住! ...
  • 前言: 本文主要是介紹了Nunit的基本使用,其中參詳了很多已有的文章,由於最近要使用其進行測試,所以對網上的文章做了下整理,同時加入了一些自己的實踐。 NUnit的屬性 TestFixture 它標記一個類包含測試,申明該類是用來測試的。一般用在class的定義之前; Test 一般是放在meth ...
  • 一、前言 最近公司新項目,需要搭架構進行開發,其中需要保證事務的一致性,經過一番查找,發現很多博文都是通過Spring.Net、Unity、PostSharp、Castle Windsor這些方式實現AOP的。但是這不是我想要的,因此一番查找後,使用 該方式實現AOP。 二、使用AOP的優勢 博主覺 ...
  • 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ClassDemo ... ...
  • C# 將Access中時間段條件查詢的數據添加到ListView中 一、讓ListView控制項顯示表頭的方法 在窗體中添加ListView 空間,其屬性中設置:View屬性設置為:Detail,Columns集合中添加表頭中的文字。 二、利用代碼給ListView添加Item。 首先,ListVie ...
  • 一、Docker for Windows 基礎知識 1. 下載docker for windows。 "docker for windows" 2. 下載安裝完後設置"Shared Drives"。 3. 因為國內訪問docker story太慢。需要設置docker加速器: "Daemon" Re ...
  • Quartz.net是作業調度框架 1. 項目中添加quartz.net的引用(這裡使用nuget管理) 新建一個類TimingJob,該類主要用於實現任務邏輯 在Program.cs中:(這裡是控制台應用程式) 程式運行時,經過5秒後,每間隔2秒輸出信息 Cron表達式: quartz.NET中的 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...