欢迎光临
我们一直在努力

自定义配置节处理实现个性化web.config-ASP教程,ASP应用

建站超值云服务器,限时71元/月

通过system.configuration中的configurationsettings类的appsettings属性,可以很方便访问web.config配置文件中appsettings节点的数据。对于web程序利用这个配置文件存放一些只读的程序信息,比如程序名称,作者信息,数据库连接字符串等将是十分方便有用。如:

<!–sample.aspx–>

private void page_load(object sender, system.eventargs e)

{

this.tbname = configurationsettings.appsettings[“appname“];

}

<!–web.config–>

<configuration>

<appsettings>

<add key="appname" value="myapplication" />

</appsettings>

… …

对于configurationsettings类有个方法getconfig(string sectionname)可以访问任何配置元素,对于以上例子,可如此使用:

<!–sample.aspx–>

private void page_load(object sender, system.eventargs e)

{

object settings = configurationsettings.getconfig(“appsettings“);

namevaluecollection nvc = settings as namevaluecollection;

if (nvc != null)

{

string val = (string)nvc[“appname“];

this.tbname = val;

}

}

可见getconfig()方法返回了一个配置处理的对象,转换成namevaluecollection的实例后,可以访问到该section内的内容了。其实对于配置文件检索有背后的处理程序实现,同时我们可以看到在web.config,或machine.config中看到对于处理程序的声明,如:

<!–web.config–>

<configuration>

<configsections>

<section name="mysection"

type="chagel.configration.settings, configuration" />

</configsections>

<mysection>

<appname> myapplication</appname>

</mysection>

… …

以上声明了一个mysection元素,并在configsections中声明了该配置的处理程序类名为chagel.configration.settings,configuration为程序集名称。接下来我们可以通过一个实现system.configuration.iconfigurationsectionhandler接口的类来处理该配置元素,如:

<!–settings.cs–>

using chagel.configration.data;

namespace chagel.configration

{

public class settings:iconfigurationsectionhandler

{ //实现该接口的create方法

public object create(object parent, object input, xmlnode node)

{

data data = new data();

foreach(xmlnode xn in node.childnodes)

{

switch(xn.name)

{

case("appname"):

data.appname = xn.innertext;

break;

case("appver"):

data.appver = xn.innertext;

break;

… …

}//switch end

}//foreach end

return data;

}//method end

}

}

iconfigurationsectionhandler 接口只有一种方法,每当发现注册到处理程序的配置节时,都会在节处理程序上调用 create 方法,我们实现的类返回一个data类的实例,该类是一个专门的数据集,代码如下:

<!–data.cs–>

namespace chagel.configration.data

{

public class data

{

public data()

{

}

public string appname;//程序名称

public string appver;//程序版本

public string appauthor;//程序作者

… …

}

}

至此,现在可以读取配置元素值了,如:

<!–sample1.aspx–>

private void page_load(object sender, system.eventargs e)

{

data data;

data = configurationsettings.getconfig("mysection") as data;

this.tbname.text = data.appname;

}

到此我们通过实现一个类支持 iconfigurationsectionhandler 接口来对自定义节进行处理,完成对自定义节的读取。当然我们仍可以直接声明系统的处理程序(system.configuration.namevaluefilesectionhandler)重用与appsettings一样的类。

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 自定义配置节处理实现个性化web.config-ASP教程,ASP应用
分享到: 更多 (0)

相关推荐

  • 暂无文章