您的位置:首页 > 其它

创建web.config自定义配置部分

2007-10-28 01:53 246 查看
今天看了一下web.config创建自定义配置部分,虽然大多数常用的应用程序专用的设置可以保存在appsettings元素中,但有时还是需要添加自定义的配置元素,增强可用的配置元素集.即是我们用不到,分析一个自定义的配置部分还是对我们更好的理解如何解析web.config有好处的.
以下举例说明,假设我们希望应用程序能够用acme元素指定自定义元素,acme元素包含在一个新的称为acmegroup的部分中,比如有一下元素:font,backgroundColor,underlineLinks,horizontalWidth,verticalWidth.
webconfig代码如下:

<configuration>

<configSections>

<sectionGroup name="acmeGroup">

<section name="acme"

type="EssentialAspDotNet.Config.AcmeConfigHandler, AcmeConfigHandler"

/>

</sectionGroup>

</configSections>

<myGroup>

<add key="font" value="Courier New"/>

<add key="backgroundColor" value="Green"/>

<add key="underlineLinks" value="true"/>

<add key="horizontalWidth" value="600"/>

<add key="verticalWidth" value="800"/>

</myGroup>

<acmeGroup>

<acme>

<font>Courier New</font>

<backgroundColor>Green</backgroundColor>

<underlineLinks>true</underlineLinks>

<horizontalWidth>600</horizontalWidth>

<verticalWidth>800</verticalWidth>

</acme>

</acmeGroup>

<appSettings>

<add key="DSN"

value="server=localhost;uid=sa;pwd=;database=pubs"

/>

<add key="bgColor" value="blue" />

</appSettings>

</configuration>

自定义配置设置
//AcmeSettings.cs

using System;


namespace EssentialAspDotNet.Config
{
public class AcmeSettings
{
public string Font;
public string BackgroundColor;
public bool UnderlineLinks;
public int HorizontalWidth;
public int VerticalWidth;

public override string ToString()
{
return string.Format("AcmeSettings: Font={0}, BackgroundColor={1}, UnderlineLinks={2}, HorizontalWidth={3}, VerticalWidth={4}",
Font, BackgroundColor, UnderlineLinks, HorizontalWidth, VerticalWidth);
}
}
}

自定义配置部分处理程序
//AcmeConfigHandler.cs
using System;
using System.Xml;

using System.Configuration;

using System.Web;

using System.Web.Configuration;

namespace EssentialAspDotNet.Config

{

public class AcmeConfigHandler : IConfigurationSectionHandler

{

public object Create(object parent, object input, XmlNode node)

{

AcmeSettings aset = new AcmeSettings();

foreach (XmlNode n in node.ChildNodes)

{

switch (n.Name)

{

case ("font"):

aset.Font = n.InnerText;

break;

case ("backgroundColor"):

aset.BackgroundColor = n.InnerText;

break;

case ("underlineLinks"):

aset.UnderlineLinks = bool.Parse(n.InnerText);

break;

case ("horizontalWidth"):

aset.HorizontalWidth = int.Parse(n.InnerText);

break;

case ("verticalWidth"):

aset.VerticalWidth = int.Parse(n.InnerText);

break;

}

}

return aset;

}

}

}

未完待续:访问自定义配置信息,使用NameValueFileSectionHandler
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: