一.寫作前題
我們用ASP.NET做項目開發的時候,配置Config文件那是經常的事情,VS.NET的Config文件提供了很多節,但是往往提供的這些配置信息還不能夠完全滿足我們的項目開發需求,而且微軟正是考慮到這方面的因素,他允許用戶自定義Configuration的相關配置內容。本文就此寫了一些實例,希望對大家有所幫助。
二.本文內容
1.實現web.config中的自定義
2.對自定義節的使用
3.本文總結
三.實現Web.Config中自定義節
廢話不多說,直接說主題,這里我們要繼承ConfigurationElement,ConfigurationElementCollection,ConfigurationSection等相關的類。
首先我們在Config文件中的增加了一個節,我們增加了一個自定義節<section name="commonSectionConfiguration" type="CWS.Framework.Client.ClientAddressSection,CWS.Framework.Client"/>,這個節的具體配置如下所示
1 <commonSectionConfiguration>
2 <CleintAddressCollection>
3 <add Name="CommonPath" ServiceCommonPath="http://localhost/CWSHost/SVCService/{0}" IsDefault="true">add>
4 CleintAddressCollection>
5 commonSectionConfiguration>
Config文件的整體配置如下所示:
1 <configuration>
2 <configSections>
3 <section name="commonSectionConfiguration" type="CWS.Framework.Client.ClientAddressSection,CWS.Framework.Client"/>
4 <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
5 <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
6 <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
7 <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
8 <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
9 <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
10 <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
11 <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
12 sectionGroup>
13 sectionGroup>
14 sectionGroup>
15 configSections>
16 <commonSectionConfiguration>
17 <CleintAddressCollection>
18 <add Name="CommonPath" ServiceCommonPath="http://localhost/CWSHost/SVCService/{0}" IsDefault="true">add>
19 CleintAddressCollection>
20 commonSectionConfiguration>
21 configuration>
通過上面的web.config文件,我本文所使用的自定義節的使用,設置完web.config文件后,我們怎么來使用(獲得)我們配置的信息呢? 我們可以從上面看到 type="CWS.Framework.Client.ClientAddressSection,CWS.Framework.Client", 這就告訴我們,通過CWS.Framework.Client命名空間下的ClientAddressSection類來實現這個節的操作。
為了實現對這個節的使用,需要寫一個類,他繼承于ConfigurationElement類,實現對config中自定義節CleintAddressCollection中屬性的映射,請看下面代碼。

映射web.config自定義類
1 /***********************************************************
2 * @Copy Right CWS.Framework.Client V1.0
3 * Function: Provid a class to mapping the web config
4 *
5 * Create By:Xiong Wei Date: 22 August 2009
6 * Update By: Date:
7 *
8 * Review History:
9 * Review By/Date Description
10 *
11 ***********************************************************/
12 using System;
13 using System.Collections.Generic;
14 using System.Linq;
15 using System.Text;
16 using System.Configuration;
17
18 namespace CWS.Framework.Client
19 {
20 ///
21 /// mapping with configuration file
22 ///
23 public sealed class ClientAddressElement : ConfigurationElement
24 {
25 [ConfigurationProperty("Name")]
26 public string Name
27 {
28 get { return this["Name"] as string; }
29 set { this["Name"] = value; }
30 }
31
32 [ConfigurationProperty("ServiceCommonPath")]
33 public string ServiceCommonPath
34 {
35 get { return (string)this["ServiceCommonPath"]; }
36 set { this["ServiceCommonPath"] = value; }
37 }
38
39 [ConfigurationProperty("IsDefault")]
40 public bool IsDefault
41 {
42 get { return (bool)this["IsDefault"]; }
43 set { this["IsDefault"] = value; }
44 }
45 }
46 }
47
通過上面的代碼我們可以看到,他實現了對config中CleintAddressCollection屬性的映射。在本文中我們只有三個屬性,如果有更多的屬性我們可以以此類推,實現代碼與Config文件中屬性的映射關系。
上面我們只是寫了一個類來實現對config中屬性的映射,但是如何使用這個類呢,請看下面的代碼。


創建自定義節對象
1 /***********************************************************
2 * @Copy Right CWS.Framework.Client V1.0
3 * Function: Get user-defined section
4 *
5 * Create By:Xiong Wei Date: 22 August 2009
6 * Update By: Date:
7 *
8 * Review History:
9 * Review By/Date Description
10 *
11 ***********************************************************/
12 using System;
13 using System.Collections.Generic;
14 using System.Linq;
15 using System.Text;
16 using System.Configuration;
17
18 namespace CWS.Framework.Client
19 {
20 [ConfigurationCollection(typeof(ClientAddressElement))]
21 public sealed class ClientAddressElementCollection : ConfigurationElementCollection
22 {
23 static ClientAddressElementCollection()
24 {
25
26 }
27
28 public new ClientAddressElement this[string key]
29 {
30 get { return (ClientAddressElement)base.BaseGet(key); }
31 set { base.BaseRemove(key); this.BaseAdd(value); }
32 }
33
34 protected override ConfigurationElement CreateNewElement()
35 {
36 return new ClientAddressElement();
37 }
38
39 protected override object GetElementKey(ConfigurationElement element)
40 {
41 return ((ClientAddressElement)element).Name;
42 }
43 }
44 }
45
上面我們在重載方法GetElementKey中指定用Name用為唯一屬性。比如說在自定義的節中有多個item,那么我們怎么知道我們需要那一個item呢,這時就需要使用Name來進行標識。
<commonSectionConfiguration>
<CleintAddressCollection>
<add Name="CommonPath" ServiceCommonPath="http://localhost/CWSHost/SVCService/{0}" IsDefault="true">add>
<add Name="CommonPath1" ServiceCommonPath="http://localhost/DUPHost/SVCService/{0}" IsDefault="true">add>
CleintAddressCollection>
commonSectionConfiguration>
下面這段代碼的作用,是取出我們所需要的那個section的內容,因為我們可能有多個section的類容,我們怎么知道我們現在需要使用那個section的內容,比如說下面的代碼,我們就是告訴我們需要取出
CleintAddressCollection節中的信息。

提取節的代碼
1 /***********************************************************
2 * @Copy Right CWS.Framework.Client V1.0
3 * Function: Provid a class to mapping the section in web config
4 *
5 * Create By:Xiong Wei Date: 22 August 2009
6 * Update By: Date:
7 *
8 * Review History:
9 * Review By/Date Description
10 *
11 ***********************************************************/
12 using System;
13 using System.Collections.Generic;
14 using System.Linq;
15 using System.Text;
16 using System.Configuration;
17
18 namespace CWS.Framework.Client
19 {
20 public sealed class ClientAddressSection : ConfigurationSection
21 {
22 private static readonly ConfigurationProperty _propertyItems;
23 private static ConfigurationPropertyCollection _properties;
24
25 static ClientAddressSection()
26 {
27 _propertyItems = new ConfigurationProperty("CleintAddressCollection", typeof(ClientAddressElementCollection), null, ConfigurationPropertyOptions.IsRequired);
28 _properties = new ConfigurationPropertyCollection();
29 _properties.Add(_propertyItems);
30 }
31
32 [ConfigurationProperty("CleintAddressCollection")]
33 public ClientAddressElementCollection CleintAddressCollection
34 {
35 get { return (ClientAddressElementCollection)base[_propertyItems]; }
36 set { base[_propertyItems] = value; }
37 }
38
39 protected override ConfigurationPropertyCollection Properties
40 {
41 get
42 {
43 return _properties;
44 }
45 }
46 }
47 }
48
上面的代碼已經為我們取出了所需要的屬性,下面我們要做的就是取出這些值,這里就涉及到具體的應用,可以根據自己的需求不定進行自定義的設置。

實現對自定義節的引用
1 /***********************************************************
2 * @Copy Right CWS.Framework.Client V1.0
3 * Function: Usage the user-defined configuration section information
4 *
5 * Create By:Xiong Wei Date: 22 August 2009
6 * Update By: Date:
7 *
8 * Review History:
9 * Review By/Date Description
10 *
11 ***********************************************************/
12 using System;
13 using System.Collections.Generic;
14 using System.Linq;
15 using System.Text;
16 using System.Configuration;
17
18 namespace CWS.Framework.Client
19 {
20 public static class ClientAddressOpreate
21 {
22 public static string GetCommonPath()
23 {
24 Configuration config = ConfigurationManager.OpenExeConfiguration(string.Empty);
25 ClientAddressSection section = config.GetSection("commonSectionConfiguration") as ClientAddressSection;
26 string elementKey = "CommonPath";
27 ClientAddressElement proitem = section.CleintAddressCollection[elementKey];
28 if (proitem == null)
29 {
30 throw new Exception("None object when get the client common address path");
31 }
32 return proitem.ServiceCommonPath;
33 }
34 }
35 }
36
在我們的例子中,我們提供了一個方法來實現上面功能的調用。

提供可被調用方法
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace CWS.Framework.Client
7 {
8 public static class UrlHelper
9 {
10 public static string GetWCFUrl(string endpointSVCName)
11 {
12 return string.Format(ClientAddressOpreate.GetCommonPath(), endpointSVCName);
13 }
14 }
15 }
16
四.引用自定義節
上面第三節內容的代碼我們已經實現了地自定節的實現和操作,下面的類是一個aspx.cs文件,他的作用就是調用上面實現的功能,并把結果輸出出來。

Code
1 using System;
2 using System.Collections;
3 using System.Configuration;
4 using System.Data;
5 using System.Linq;
6 using System.Web;
7 using System.Web.Security;
8 using System.Web.UI;
9 using System.Web.UI.HtmlControls;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 using System.Xml.Linq;
13 using CWS.Framework.Client;
14
15 namespace Demo
16 {
17 public partial class _Default : System.Web.UI.Page
18 {
19 protected void Page_Load(object sender, EventArgs e)
20 {
21 Response.Write(UrlHelper.GetWCFUrl("test"));
22 }
23 }
24 }
輸出結果如下:

五.總結
1.通過此實現為以后開發其它產品實現自定義類提供了參考。
2.實現功能,需要理解web.config與實際代碼之間的映射關系。
3.對System.Configuration命名空間下的ConfigurationElement,ConfigurationElementCollection,ConfigurationSection類的要有所了解。