web.config中configSections section节 -Z
由于最近一个项目的数据库变动比较频繁, 为了减少数据层的负担, 打算采用.net的MVC框架, 使用LINQ对付数据层.
<configSections>
<section name="NameM" type="LearningConfiguration.NameSectionHandler"/>
</configSections>
<NameM>
<Add key="name1" firstname="Jim" lastname="w1"/>
<Add key="name2" firstname="Chris" lastname="w2"/>
</NameM>
Code
namespace LearningConfiguration
{
public class NameSectionHandler : IConfigurationSectionHandler
{
#region IConfigurationSectionHandler Members
public object Create(object parent, object configContext, XmlNode section)
{
Dictionary<string, NameManagement> names = new Dictionary<string, NameManagement>();
string key = string.Empty;
string firstName = string.Empty;
string lastName = string.Empty;
foreach (XmlNode childNode in section.ChildNodes)
{
if (childNode.Attributes["key"] != null)
{
key = childNode.Attributes["key"].Value; if (childNode.Attributes["firstname"] != null)
{
firstName = childNode.Attributes["firstname"].Value;
}
else
{
firstName = string.Empty;
}
if (childNode.Attributes["lastname"] != null)
{
lastName = childNode.Attributes["lastname"].Value;
}
else
{
lastName = string.Empty;
}
names.Add(key, new NameManagement(firstName, lastName));
}
}
return names;
}
#endregion
}
}
namespace LearningConfiguration
{
public class NameManagement
{
string _firstName;
public string FirstName
{
get { return this._firstName; }
set { this._firstName = value; }
}
string _lastName;
public string LastName
{
get { return this._lastName; }
set { this._lastName = value; }
}
public NameManagement(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
public string RetrieveFullName()
{
return string.Format("{0} {1}", this.FirstName, this.LastName);
}
}
}
namespace LearningConfiguration
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<string, NameManagement> names = ConfigurationManager.GetSection("NameM") as Dictionary<string, NameManagement>;
if (names != null)
{
foreach(string key in names.Keys)
{
NameManagement name = names[key] as NameManagement;
Response.Write(name.RetrieveFullName());
}
}
}
}
}
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Collections.Specialized;
using LearningConfiguation; public partial class Default4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<String, NameManagement> names = System.Configuration.ConfigurationManager.GetSection("test/aa") as Dictionary<String, NameManagement>;
Dictionary<String, NameManagement>.KeyCollection keys = names.Keys;
foreach (String key in keys)
{
NameManagement nm = names[key] as NameManagement;
Response.Write(nm.FirstName);
Response.Write("<br>");
Response.Write(nm.LastName);
}
}
}
为了增加应用程序的可移植性,通常网站需要配置一些自定义的节点,例如:文件上传的路径等,再深入的应用,可以定义工厂方法需要创建的类。
2.configSections使用方法
configSections节点下定义自定义节点可以帮我们实现我们自己的节点。
首先定义自己的节点,定义方法如下:
<configSections>
<sectionGroup name="section group name">
<section name="section name" type="configuration section handler class" />
</sectionGroup>
</configSections>
定义自己的节点必须在configSections节点。
sectionGroup 元素充当 section 元素的容器。
section 元素将配置节处理程序与配置元素或节关联。由于 ASP.NET 不对如何处理配置文件内的设置作任何假设,因此这非常必要。但 ASP.NET 会将配置数据的处理委托给配置节处理程序,(稍候说明。)每个 section 元素均标识一个配置节或元素。可以在 sectionGroup 元素中对 section 元素进行逻辑分组,以对 section 元素进行组织并避免命名冲突。section 和 sectionGroup 元素包含在 configSections 元素中。
sectionGroup节点属性:
name:必选的 String 属性,这是 group 元素在配置文件的节设置区域中使用的名称。
section节点属性:
name:必选的 String 属性,指定与 type 属性中指定的配置节处理程序关联的配置节或元素的名称。这是该元素在配置文件的节设置区域中使用的名称。
type:必选的 String 属性,指定用来执行如下操作的配置节处理程序类的名称:处理在 name 属性中指定的节或元素中的配置设置。
现在定义好了自己的节点,可以使用该节点了。使用方法如下:
<section group name>
<section name>
<add key="key1" value="value1" />
</section name>
</section group name>
定义好了自己的节点,如何读取节点信息呢?
以下是msdn上的原话:
您可以用自己的 XML 配置元素来扩展标准的 ASP.NET 配置设置集。若要完成该操作,您必须创建自己的配置节处理程序。
该处理程序必须是一个实现 System.Configuration.IConfigurationSectionHandler 接口或 System.Configuration.ConfigurationSection 类的 .NET Framework 类。
节处理程序解释并处理 Web.config 文件特定部分中 XML 配置元素中定义的设置,并根据配置设置返回适当的配置对象。处理程序类返回的配置对象可以是任何数据结构;它不限于任何基配置类或配置格式。ASP.NET 使用该配置对象,以对自定义配置元素进行读取和写入。
上面这段话的意思就是说,我们要定义一个类,这个类要继承自System.Configuration.IConfigurationSectionHandler 接口或 System.Configuration.ConfigurationSection 类。
然后用这个类来处理我们自定义的节点。
我们看到System.Configuration.IConfigurationSectionHandler接口中,只有一个方法:
//创建配置节处理程序
Object Create (Object parent, Object configContext, XmlNode section)
返回值
创建的节处理程序对象。
这个类是干什么用的呢?让我们通过一个例子来看看。
首先,我们新建一个网站项目,并在web.config中加入以下节点:
<configSections>
<sectionGroup name="WebSiteInfo">
<section name="basicInfo" type="ConfigurationSectionTest.WebSiteInfoHandler"/>
<section name="fileUpload" type="ConfigurationSectionTest.WebSiteInfoHandler"/>
</sectionGroup>
</configSections>
<WebSiteInfo>
<basicInfo>
<add key="name" value="huchen's homepage"/>
<add key="version" value="1.0"/>
</basicInfo>
<fileUpload>
<add key="fileUploadPath" value="E:\\MyHomePage\\Web\\Upload\\"/>
<add key="fileUploadSizeMax" value="2M"/>
</fileUpload>
</WebSiteInfo>
以上我们在WebSiteInfo节点下定义了两个节点basicInfo和fileUpload,并定义了节点处理程序类ConfigurationSectionTest.WebSiteInfoHandler,并且随后运用了我们定义的节点。
我们来看看节点处理程序ConfigurationSectionTest.WebSiteInfoHandler。
任意建立一个项目,新建一个类,或者直接在App_Code里新建一个类,如下:
并在Create函数中设置一个断点。
namespace ConfigurationSectionTest
{
/// <summary>
///WebSiteInfoHandler 的摘要说明
/// </summary>
public class WebSiteInfoHandler : IConfigurationSectionHandler
{
public WebSiteInfoHandler()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
#region IConfigurationSectionHandler 成员
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
//这里我们首先返回个hello,并且在此处设置一个断点。看看程序什么时候执行到这。
return "hello";
}
#endregion
}
}
然后在Default.aspx的Page_Load事件处理程序中去访问我们自定义的节点,并在ConfigurationSettings.GetConfig("WebSiteInfo/basicInfo"); 这条语句上设置断点。
protected void Page_Load(object sender, EventArgs e)
{
Object o = ConfigurationSettings.GetConfig("WebSiteInfo/basicInfo");
}
好了,我们启动调试,看到程序首先执行到ConfigurationSettings.GetConfig("WebSiteInfo/basicInfo");这句。
然后执行到ConfigurationSectionTest.WebSiteInfoHandler中的Create函数。
我们再看看这时处理函数中参数的值:
parent为null
configContext 为配置上下文对象。
section 的InnerXml为<add key="name" value="huchen's homepage" /><add key="version" value="1.0" />
按F11继续执行return "hello", 继续执行...
在执行到Object o = ConfigurationSettings.GetConfig("WebSiteInfo/basicInfo")后面的“}“,我们发现o的值为”hello”。
相信您已经明白的差不多了,当读取自定义节点的内容时,程序去执行我们定义的节点处理程序,并把节点中的内容传给Create函数中的参数。然后我们在Create中自己处理节点下的内容,并返回我们格式化后的节点内容给调用者,也就是ConfigurationSettings.GetConfig("WebSiteInfo/basicInfo")。
注意:程序第一次运行的时候可以调试到Create这个方法,第二次运行的时候就调试不到了,这是因为配置文件时缓存了起来.
只有改变了配置文件或者继承自IConfigurationSectionHandler的类才会重新调用.
好,知道这些以后,我们就来完善我们的代码,我们在Create中处理传进来的节点内容。
为了简单起见,我们引入两个类NameValueCollection,NameValueSectionHandler。
NameValueCollection:表示可通过键或索引访问的关联 String 键和 String 值的集合。
NameValueSectionHandler:提供配置节中的名称/值对配置信息。NameValueSectionHandler 这个类也继承IConfigurationSectionHandler
反编译可以看出NameValueSectionHandler 的Create方法把参数section的结果转化成了一个集合,就是NameValueCollection。
那么我们可以在节点处理程序中的Create函数中写如下代码:
NameValueCollection configs;
NameValueSectionHandler baseHandler = new NameValueSectionHandler();
configs =(NameValueCollection)baseHandler.Create(parent,configContext,section);
Return configs;
这样我们就可以这样访问我们的节点了:
string myWebSiteName = ((NameValueCollection)ConfigurationSettings.GetConfig("WebSiteInfo/basicInfo"))["name"];
在Default.aspx的Page_Load事件处理程序中添加如下代码:
string myWebSiteName = ((NameValueCollection)ConfigurationSettings.GetConfig("WebSiteInfo/basicInfo"))["name"];
Response.Write(myWebSiteName);
Ctrl+F5运行,可以看到页面输出了huchen's homepage
web.config中configSections section节 -Z的更多相关文章
- 通过Web.config中的configSections配置自己系统的全局常量
通过Web.config中的configSections配置自己系统的全局常量 随着系统的庞大,你的全局信息保存在appsitting里可能会比较乱,不如为模块写个自定义的全局常量吧 首先在Web.C ...
- ASP.NET web.config中数据库连接字符串connectionStrings节的配置方法
ASP.NET web.config中数据库连接字符串connectionStrings节的配置方法 第一种情况,本地开发时,使用本地数据库,如下面的代码 <connectionStrings& ...
- 使用IConfigurationSectionHandler在web.config中增加自定义配置
一. 场景 这里仅举一个简单应用的例子,我希望在web.config里面增加网站的基本信息,如:网站名称,网站版本号,是否将网站暂时关闭等.二. 基本实现方法1. 定义配置节点对应的类:Site ...
- web.config中authorization下的location中的path的设置 (转)
项目下 有三个文件夹 A,B,C 验正方式是 Forms 验正 我要设置他们的访问权限为, A,匿名可访问 B,普通用户授权后才能访问 C,只允许管理员访问 <configuration> ...
- 释放SQL Server占用的内存 .Net 读取xml UrlReWriter 在web.config中简单的配置
释放SQL Server占用的内存 由于Sql Server对于系统内存的管理策略是有多少占多少,除非系统内存不够用了(大约到剩余内存为4M左右),Sql Server才会释放一点点内存.所以很多 ...
- [转]通过继承ConfigurationSection,在web.config中增加自定义配置
本文转自:http://www.blue1000.com/bkhtml/2008-02/55810.htm 前几天写了一篇使用IConfigurationSectionHandler在web.conf ...
- web.config中配置页面出错后跳转指定错误页面
每当用户访问错误页面时,会出现不友好的404错误,所以为了防止这种不友好,我们在web.config中的<system.web>节点下配置 <customErrors>,在出现 ...
- (译)利用ASP.NET加密和解密Web.config中连接字符串
介绍 这篇文章我将介绍如何利用ASP.NET来加密和解密Web.config中连接字符串 背景描述 在以前的博客中,我写了许多关于介绍 Asp.net, Gridview, SQL Server, A ...
- 利用ASP.NET加密和解密Web.config中连接字符串
摘自:博客园 介绍 这篇文章我将介绍如何利用ASP.NET来加密和解密Web.config中连接字符串 背景描述 在以前的博客中,我写了许多关于介绍 Asp.net, Gridview, SQL Se ...
随机推荐
- ASP.NET Core轻松入门之Configure中IHostingEnvironment和IApplicationLifetime的使用
在StratUp.cs的Configure方法中,除了 常用的参数除了IApplicationBuilder和在我上一篇文章中提到的Iconfiguration点击打开链接 外 还有 IHostin ...
- iBatis基础知识
iBatis简介: 特点:结构性好,小巧,容易上手 搭建环境: 1.创建java 项目 2.导入(3个)jar包:ibatis-2.3.0.667.jar,mysql驱动包,Junit测试包 3.配置 ...
- 使用 LINQPad 助力 LINQ 学习
简介一图示意 简介 LINQPad 是一款学习 LINQ,优化 SQL 的好助手. 它的一大特点是内置了新版<C# in a Nutshell>的全部 LINQ 示例,不管是配合原书进行练 ...
- numpy使用总结
numpy是Python中常用的数据处理库的基础库,一般通过import numpy as np的方式导进 科学计算库numpy 在numpy中,主要的数据结构是ndarray,在numpy中称为数组 ...
- 使用Spring-hadoop小结
SpringHadoop是通过Spring框架来调用hdfs,跟直接调用hdfs的最大的不同区别是Spring通过依赖注入的方式生成操作hdfs所需要的configuration和filesystem ...
- [BZOJ1609] [Usaco2008 Feb] Eating Together麻烦的聚餐 (dp)
Description 为了避免餐厅过分拥挤,FJ要求奶牛们分3批就餐.每天晚饭前,奶牛们都会在餐厅前排队入内,按FJ的设想所有第3批就餐的奶牛排在队尾,队伍的前端由设定为第1批就餐的奶牛占据,中间的 ...
- 论文笔记(7):Constrained Convolutional Neural Networks for Weakly Supervised Segmentation
UC Berkeley的Deepak Pathak 使用了一个具有图像级别标记的训练数据来做弱监督学习.训练数据中只给出图像中包含某种物体,但是没有其位置信息和所包含的像素信息.该文章的方法将imag ...
- c# List实现原理
在研究前辈们写的代码,总是搞不明白.word文中引文的索引和引文列表中的索引对应关系是什么呢?是如何对应上的?我冥思苦想,昨天又系统地看了下代码,才所有悟,所以记录下我的探索过程. 如下图所示: 图1 ...
- 基于规则评分的密码强度检测算法分析及实现(JavaScript)
简言 用正则表达式做用户密码强度的通过性判定,过于简单粗暴,不但用户体验差,而且用户帐号安全性也差.那么如何准确评价用户密码的强度,保护用户帐号安全呢?本文分析介绍了几种基于规则评分的密码强度检测算法 ...
- es6学习笔记--新数据结构Set,Map以及WeakSet,WeakMap
在javascript中,存储数据的方式大部分就是以数组或者对象形式存储的,es6出现了4种新集合Set,Map,WeakSet,WeakMap来存储数据,简化了编程. 集合--Set 类似于数组,但 ...