在开发Asp.net站点的时候,我们会遇到很多的配置参数:网站名称,上传图片后缀,上传文件后缀,关键字过滤,数据库连接字串等等,这些内容如果比较少的话,直接配置到Web.config文件中,借由.NET提供的操作类,将会非常方便的来操作这些自定义配置节点,
参考:http://www.cnblogs.com/scy251147/archive/2011/12/29/2306504.html
首先,配置一个最简单的节点
<MySection username="程序诗人" url="http://scy251147.cnblogs.com" comment="注意啦!!!!!!" />
这个该如何来进行呢?
在Web.Config中,如果想配置这样的自定义节点,需要首先在configuration节点下的configSections节点中进行注册,如下:
<section name="MySection" type="WebApplication1.MySection,WebApplication1"/>这样,我们只需要将MySection节点配置在configuration节点下即可,具体的ScreenShot如下:
那么如何在界面上展示出来呢?首先得需要定义一个类继承自ConfigurationSection才可以继续后面的操作.
using System.Configuration;
namespace WebApplication1
{
public class MySection:ConfigurationSection
{
[ConfigurationProperty("username", IsRequired = true)]
public string UserName
{
get { return this["username"].ToString(); }
set { this["username"] = value; }
}
[ConfigurationProperty("url", IsRequired = true)]
public string Url
{
get { return this["url"].ToString(); }
set { this["url"] = value; }
}
[ConfigurationProperty("comment", IsRequired = true)]
public string Comment
{
get { return this["comment"].ToString(); }
set { this["comment"] = value; }
}
}
}
在界面上可以通过如下方式来显示:
MySection mySection = (MySection)ConfigurationManager.GetSection("MySection"); Response.Write(mySection.UserName + "----" + mySection.Url+"----"+mySection.Comment);其次 对于一个稍微复杂一点的自定义节点,这个自定义节点下面有子节点,这个该如何来进行呢?类似:
<MySectionWithChild>
<users username="程序诗人" url="http://scy251147.cnblogs.com" comment="注意啦!!!!!" />
</MySectionWithChild>
这个在Web.Config中的配置和前面类似,就是先注册节点,然后将节点放到configuration节点下:
当然,如果要访问这个自定义节点,也需要通过类来配置,我们得首先定义一个父节点类,父节点类包含子节点元素:
父节点类:
using System.Configuration;
namespace WebApplication1
{
public class MySectionParent:ConfigurationSection
{
[ConfigurationProperty("users", IsRequired = true)]
public MySectionWithChild Users
{
get { return (MySectionWithChild)this["users"]; }
}
}
}