解决在Web.config或App.config中添加自定义配置的方法详解
ASP NET自定义配置文件设置(以及修改Entity Framework数据库连接为自定义字符串)

自定义配置文件设置在开发的过程中,我们经常会遇到在开发、测试、发布部署等不同的环境下使用不同的连接字符串,WebAPI的连接。
为了避免频频复杂的修改各个配置,因此用到了自定义配置文件设置。
此篇文章使用的自定义配置文件方法为:web.config 增加自定义Section节,相关配置全部放到webconfig。
一、配置Web.config文件。
1.0首先需要在configuration节点下的configSections节点中进行注册,如下:<section name="ConnectionStringSection"type="CustomConfig.Configrationner.ConnectionStringSection, CustomConfig" />注:CustomConfig.Configrationner.ConnectionStringSection指的是:此section 可解析的实体所存放的【完整的命名空间.类名】,CustomConfig 指的是:此section所在的程序集(dll)的名称。
2.0然后将ConnectionStringSection节点配置在configuration节点下即可,具体如下:二、配置调用ConfigrationSection的文件。
1.0首先要访问这个自定义节点,需要通过类来配置,我们得首先定义一个父节点类,父节点类包含子节点集合,如下:namespace CustomConfig.Configrationner{public class ConnectionStringSection : ConfigurationSection{[ConfigurationProperty("Publish")]public ConnectionStringCollection Publish{get { return (ConnectionStringCollection)this["Publish"]; }}[ConfigurationProperty("Develop")]public ConnectionStringCollection Develop{get { return (ConnectionStringCollection)this["Develop"]; }}[ConfigurationProperty("Test")]public ConnectionStringCollection Test{get { return (ConnectionStringCollection)this["Test"]; }}}}2.0子节点集合再包含子节点元素,如下namespace CustomConfig.Configrationner{public class ConnectionStringCollection : ConfigurationElementCollection{protected override ConfigurationElement CreateNewElement() {return new NameValueSettings();}protected override object GetElementKey(ConfigurationElement element) {return ((NameValueSettings)element).Name;}//写一个索引器,方便的访问该集合中的元素。
自定义web.config节点

在web.config中配置自定义节点配置文件的层次结构:<?xml version="1.0"encoding="utf-8"?><configuration><configSections><section name="buildingCollection"type="命名空间.BuildingSection"/></configSections><buildingCollection><buildingElement uniqueid="001"description="一号语音楼"floornum="6"></buildingElement><buildingElement uniqueid="002"description="二号行软楼"floornum="4"></buildingElement><buildingElement uniqueid="003"description="三号通信楼"floornum="2"></buildingElement></buildingCollection><appSettings><!--系统管理员角色名--><add key="AdminRoleName"value="系统管理员"/></appSettings><connectionStrings><add name="ConnectionString"connectionString="User ID=sa;Initial Catalog=databaseName;Data Source=databaseIP;Password=databasePassword"/></connectionStrings></configuration>对<configSections>的自定义配置节点类:using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;namespace mon{public class BuildingConfigHelper{public BuildingConfigHelper(){}}public class BuildingSection : ConfigurationSection{[ConfigurationProperty("", IsDefaultCollection = true)]public BuildingElementCollection BuildingCollection{get{return (BuildingElementCollection)base[""];}}}public class BuildingElementCollection : ConfigurationElementCollection {protected override ConfigurationElement CreateNewElement(){return new BuildingElement();}protected override object GetElementKey(ConfigurationElement element) {BuildingElement buildingElement = element as BuildingElement;return buildingElement.UniqueID;}public override ConfigurationElementCollectionType CollectionType{get{ return ConfigurationElementCollectionType.BasicMap; }}protected override string ElementName{get{ return"buildingElement"; }}}public class BuildingElement : ConfigurationElement{[ConfigurationProperty("uniqueid", IsRequired = true)]public string UniqueID{get { return (string)base["uniqueid"];}set { base["uniqueid"] = value; }}[ConfigurationProperty("description", IsRequired = true)]public string Description{get{ return (string)base["description"];}set{ base["description"] = value; }}[ConfigurationProperty("floornum", IsRequired = true)]public string FloorNum{get{ return (string)base["floornum"];}set{ base["floornum"] = value; }}}}自定义配置节点:///<summary>///楼号的数据绑定///</summary>private void DataBindBuilding(){BuildingSection buildingSection = ConfigurationManager.GetSection("buildingCollection") as BuildingSection;foreach (BuildingElement Building in buildingSection.BuildingCollection){string id = Building.UniqueID;string text = Building.Description;}this.ddlBuilding.Items.Clear();this.ddlBuilding.DataSource = buildingSection.BuildingCollection;this.ddlBuilding.DataTextField = "Description";this.ddlBuilding.DataValueField = "UniqueID";this.ddlBuilding.DataBind();this.ddlBuilding.SelectedIndex = 0;}///<summary>///楼层的数据绑定///</summary>///<param name="buildingid"></param>private void DataBindFloor(string buildingid){this.ddlFloor.Items.Clear();BuildingSection buildingSection = ConfigurationManager.GetSection("buildingCollection") as BuildingSection;foreach (BuildingElement Building in buildingSection.BuildingCollection){if( Building.UniqueID.Equals(buildingid)){AppBox.WebControls.ListItem item;int num = Int32.Parse(Building.FloorNum);for (int i = 0; i < num; i++){item = new AppBox.WebControls.ListItem((i + 1).ToString() + "层楼", (i + 1).ToString());this.ddlFloor.Items.Add(item);}this.ddlFloor.SelectedIndex = 0;}}}。
net中web.config一个配置文件解决方法(其他配置文件引入方式)

net中web.config⼀个配置⽂件解决⽅法(其他配置⽂件引⼊⽅式)近期⼀个项⽬需要写许多的配置项,发现在单个web.config⾥⾯写的话会很乱也难于查找所以搜了⼀下解决了,记录下来⼀、 webconfig提供了引⼊其他config的⽅式<connectionStrings configSource="Configs\database.config" />这个是连接字符串的配置你可以在database。
config⾥⾯写很多链接字符串以备⾃⼰调⽤database。
config⾥⾯的内容如下:<?xml version="1.0" encoding="utf-8"?><connectionStrings><add name="SDbContext" connectionString="Server=.;Initial Catalog=Self;User ID=sa;Password=password" providerName="System.Data.SqlClient"/> </connectionStrings><appSettings configSource="Configs\system.config" />这个是键值对的⽅式存放代码如下:<?xml version="1.0" encoding="utf-8"?><appSettings><!-- ================== 1:开发系统相关配置 ================== --><!-- 登陆提供者模式:Session、Cookie--><add key="LoginProvider" value="Cookie"/><!-- 启⽤系统⽇志--><add key="IsLog" value="true"/><!-- 数据库超时间--><add key="CommandTimeout" value="180"/><!--启⽤IP过滤 --><add key="IsIPFilter" value="false"/><!-- ================== 2:系统软件参数配置 ================== --><!-- 联系我们 --><add key="Contact" value="TE Software(Mobility)"/><!-- 软件名称 --><add key="SoftName" value="Sub Self"/><!-- 软件版本 --><add key="Version" value="1.0"/><!-- 设置就应⽤路径 --><add key="AppName" value=""/><!-- 设置就应⽤路径 --><add key="SqlGetBomList" value=""/></appSettings>以上两个是不需要特殊的配置的,放到configuration⾥⾯ configSections的下⾯这样就可以⼆、下⾯介绍⾃定义配置节<configSections><section name="users" type="ValueSectionHandler"/></configSections><users configSource="users.config"></users>注意configsections⾥⾯的⼀条,是声明这是以什么组织⽅式users.config ⾥⾯的内容如下:<users><add key="beijing" value="123"></add><add key="tianjin" value="123"></add></users>获取配置的⽅式:NameValueCollection users = System.Configuration.ConfigurationManager.GetSection("users") as NameValueCollection;// Response.Write(users.Keys[0]+"</br>"+users.Keys[1]);users.Get("beijing"); 三、复杂类型:复杂类型的声明就不同了<configSections><section name="roles" type="EBuy.Chapter3.NTier.WebUI.RolesConfig, EBuy.Chapter3.NTier.WebUI"/></configSections><roles configSource="roles.config"></roles>内容如下<roles><add username="beijing" password="123"></add><add username="tianjin" password="123"></add></roles>获取⽅式:using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace EBuy.Chapter3.NTier.WebUI{public class RolesConfig : System.Configuration.IConfigurationSectionHandler{public object Create(object parent, object configContext, System.Xml.XmlNode section){return section;}}}XmlNode roles= System.Configuration.ConfigurationManager.GetSection("roles") as XmlNode;Response.Write(roles.ChildNodes [0].Attributes["username"].InnerText);还可以配置为实体using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace EBuy.Chapter3.NTier.WebUI{public class RolesConfig : System.Configuration.IConfigurationSectionHandler{public object Create(object parent, object configContext, System.Xml.XmlNode section){var list=new List<Role>();for(int i=0;i<section.ChildNodes.Count;i++){list.Add(new Role (){Username =section.ChildNodes[i].Attributes["username"].InnerText ,Password =section.ChildNodes[i].Attributes["password"].InnerText });}return list;}}public class Role{public string Username { get; set; }public string Password{get;set;}}}var roles = System.Configuration.ConfigurationManager.GetSection("roles") as List<EBuy.Chapter3.NTier.WebUI.Role >; Response.Write(roles.First ().Username);。
Web.config详解

一、认识Web.config文件Web.config 文件是一个XML文本文件,它用来储存 Web 应用程序的配置信息(如最常用的设置 Web 应用程序的身份验证方式),它可以出现在应用程序的每一个目录中。
当你通过.NET新建一个Web应用程序后,默认情况下会在根目录自动创建一个默认的Web.config文件,包括默认的配置设置,所有的子目录都继承它的配置设置。
如果你想修改子目录的配置设置,你可以在该子目录下新建一个Web.config文件。
它可以提供除从父目录继承的配置信息以外的配置信息,也可以重写或修改父目录中定义的设置。
(一).Web.Config是以XML文件规范存储,配置文件分为以下格式1.配置节处理程序声明特点:位于配置文件的顶部,包含在<configSections>标志中。
2.特定应用程序配置特点: 位于<appSetting>中。
可以定义应用程序的全局常量设置等信息.3.配置节设置特点: 位于<system.Web>节中,控制运行时的行为.4.配置节组特点: 用<sectionGroup>标记,可以自定义分组,可以放到<configSections>内部或其它<sectionGroup>标记的内部.(二).配置节的每一节1.<configuration>节根元素,其它节都是在它的内部.2.<appSetting>节此节用于定义应用程序设置项。
对一些不确定设置,还可以让用户根据自己实际情况自己设置用法:I.<appSettings><add key="Conntction" value="server=192.168.85.66;userid=sa;password=;database=Info;"/><appSettings>定义了一个连接字符串常量,并且在实际应用时可以修改连接字符串,不用修改程式代码. II.<appSettings><add key="ErrPage" value="Error.aspx"/><appSettings>定义了一个错误重定向页面.3.<compilation>节格式:<compilationdefaultLanguage="c#"debug="true"/>I.default language: 定义后台代码语言,可以选择C#和两种语言.IIdebug : 为true时,启动aspx调试;为false不启动aspx调试,因而可以提高应用程序运行时的性能。
web.config使用方法指南

web.config使⽤⽅法指南<connectionStrings configSource="db.config"/>外部⽂件db.config:复制代码代码如下:<connectionStrings><add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WebApplication1-20140304225906;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-WebApplication1-20140304225906.mdf"providerName="System.Data.SqlClient" /><add name="ReportServerTempDBConnectionString" connectionString="Data Source=.;InitialCatalog=ReportServerTempDB;Integrated Security=True"providerName="System.Data.SqlClient" /></connectionStrings>具体格式<节点名 configSource="配置⽂件路径"/>注意点1.如果指定了configSource,就以外部⽂件为准,web.config中connectionStrings下⾯的节点配置就⽆效了,即使web.config 中connectionStrings下⾯的连接串节点没有删除掉也是⽆效的。
App.Config详解

App.Config详解应用程序配置文件是标准的XML 文件,XML 标记和属性是区分大小写的。
它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序。
配置文件的根节点是configuration。
我们经常访问的是appSettings,它是由.Net预定义配置节。
我们经常使用的配置文件的架构是象下面的形式。
先大概有个印象,通过后面的实例会有一个比较清楚的认识。
下面的“配置节”可以理解为进行配置一个XML的节点。
1. 向项目添加app.config文件:右击项目名称,选择“添加”→“添加新建项”,在出现的“添加新项”对话框中,选择“添加应用程序配置文件”;如果项目以前没有配置文件,则默认的文件名称为“app.config”,单击“确定”。
出现在设计器视图中的app.config文件为:<?xml version="1.0 "encoding= "utf-8 " ?><configuration></configuration>在项目进行编译后,在bin/Debuge文件下,将出现两个配置文件(以本项目为例),一个名为“Jxc Management.EXE.config”,另一个名为“JxcManagement.vshost.exe.config”。
第一个文件为项目实际使用的配置文件,在程序运行中所做的更改都将被保存于此;第二个文件为原代码“app.config”的同步文件,在程序运行中不会发生更改。
2. connectionStrings配置节:请注意:如果您的SQL版本为2005 Express版,则默认安装时SQL服务器实例名为localhost/SQLExpress,须更改以下实例中“Data Source=localhost;”一句为“Data Source=localhost/SQLExpress;”,在等于号的两边不要加上空格。
Asp.net中web.config配置文件详解(二)

中web.config配置⽂件详解(⼆)摘⾃近⽇正在看,看到Web.config有很不清楚之处,特意从⽹络、MSDN搜集、归纳和整理,供⼤家分享。
在的web.config中,可以⽤两种⽅式来写连接字符串的配置。
<configuration><appSettings><add key="connstr1" value="Data Source=.;Initial Catalog=DBName;Integrated Security=true"/><add key="connstr2" value="........."></appSettings><connectionStrings><add name="connstr3" connectionString="........" /><add name="connstr4" connectionString="......" providerName="System.Data.Sqlclient"</connectionStrings></configuration>如上代码所⽰:两种⽅式为appSettings和connectionStringsappSettings:①它是1.1的时候⽤的,在vs2003中⽤的②⾥⾯存的相当于键值对的形式,key和value。
不仅仅可以存连接字符串,还可以存储⼀些配置项。
其中value中包括数据库服务器地址、⽤户名和密码、数据库名称等信息。
③在appSettings中,不能使⽤ProviderName="System.Data......."(不过如果你要⽤也可以,只要写在value⾥⾯就可以了,当成值传递过去)④在后台取值⽅式⽤代码:string conn=System.Configuration.ConfigurationManager.AppSettings["connstr";]connectionStrings:①它是2.0中新增的。
Web.config配置文件详解(新手必看)

Web.co nfig配置文件详解(新手必看)花了点时间整理了一下A SP.NE T Web.conf ig配置文件的基本使用方法。
很适合新手参看,由于W eb.co nfig在使用很灵活,可以自定义一些节点。
所以这里只介绍一些比较常用的节点。
<?xml vers ion="1.0"?><!--注意:除了手动编辑此文件以外,您还可以使用Web 管理工具来配置应用程序的设置。
可以使用V isual Stud io 中的“网站”->“As配置”选项。
设置和注释的完整列表在machi ne.co nfig.comme nts 中,该文件通常位于"Windo ws"Mi croso ft.Ne t"Fra mewor k"v2.x"Con fig 中。
--><!--Webc onfig文件是一个xml文件,conf igura tion是xml文件的根节点,由于xml 文件的根节点只能有一个,所以W ebcon fig的所有配置都是在这个节点内进行的。
--><conf igura tion><!--指定配置节和命名空间声明。
clea r:移除对继承的节和节组的所有引用,只允许由当前secti on 和secti onGro up 元素添加的节和节组。
re move:移除对继承的节和节组的引用。
sec tion:定义配置节处理程序与配置元素之间的关联。
secti onGro up:定义配置节处理程序与配置节之间的关联。
--><c onfig Secti ons><sect ionGr oup n ame="syste m.web.exte nsion s"ty pe="S ystem.Web.Confi gurat ion.S ystem WebEx tensi onsSe ction Group,Sys tem.W eb.Ex tensi ons,Versi on=1.0.61025.0, Cult ure=n eutra l,Pu blicK eyTok en=31bf3856ad364e35"><secti onGro up na me="s cript ing"type="Syst em.We b.Con figur ation.Scri pting Secti onGro up, S ystem.Web.Exten sions,Ver sion=1.0.61025.0, Cu lture=neut ral,Publi cKeyT oken=31bf3856ad364e35"> <s ectio n nam e="sc riptR esour ceHan dler"type="Sys tem.W eb.Co nfigu ratio n.Scr iptin gScri ptRes ource Handl erSec tion,Syst em.We b.Ext ensio ns, V ersio n=1.0.61025.0,Cultu re=ne utral,Pub licKe yToke n=31b f3856ad364e35"requi rePer missi on="f alse"allo wDefi nitio n="Ma chine ToApp licat ion"/></sect ionGr oup></sec tionG roup> <sec tionname="rewr iter"type="Int ellig encia.UrlR ewrit er.Co nfigu ratio n.Rew riter Confi gurat ionSe ction Handl er, I nt ell igenc ia.Ur lRewr iter" /></co nfigS ectio ns><!--ap pSett ings是应用程序设置,可以定义应用程序的全局常量设置等信息--><appS ettin gs><add key="1" v alue="1" /><add k ey="g ao" v alue="weip eng"/></app Setti ngs><!--连接字符串设置--><co nnect ionSt rings> <ad d nam e="Co nnStr ing"conne ction Strin g="Da ta So urce=GAO;I nitia lCat alog=HBWXD ate;U ser I D=sa;passw ord=s a"></add><addname="111" conn ectio nStri ng="11111" /></co nnect ionSt rings><!--指定应用子配置设置的资源,并锁定配置设置,以防止它们被子配置文件重写。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
解决在Web.config或App.config中添加自定义配置的方法详解本篇文章是对在Web.config或App.config中添加自定义配置的方法进行了详细的分析介绍,需要的朋友参考下.Net中的System.Configuration命名空间为我们在web.config或者app.config中自定义配置提供了完美的支持。
最近看到一些项目中还在自定义xml文件做程序的配置,所以忍不住写一篇用系统自定义配置的随笔了。
如果你已经对自定义配置了如指掌,请忽略这篇文章。
言归正传,我们先来看一个最简单的自定义配置<?xml version="1.0" encoding="utf-8" ?><configuration><configSections><section name="simple"type="ConfigExample.Configuration.SimpleSection,ConfigExample"/></configSections><simple maxValue="20" minValue="1"></simple></configuration>在配置文件中使用自定义配置,需要在configSections中添加一个section元素,并制定此section元素对应的类型和名字。
然后再在configuration根节点下面添加此自定义配置,如上例中的simple节点。
simple节点只有两个整形数的属性maxValue和minValue。
要在程序中使用自定义配置我们还需要实现存取这个配置块的类型,一般需要做如下三件事:1. 定义类型从System.Configuration.ConfigurationSection继承2. 定义配置类的属性,这些属性需要用ConfigurationProperty特性修饰,并制定属性在配置节中的名称和其他一些限制信息3. 通过基类的string索引器实现属性的get ,set非常简单和自然,如下是上面配置类的实现:public class SimpleSection:System.Configuration.ConfigurationSection{[ConfigurationProperty("maxValue",IsRequired=false,DefaultValue=Int32.MaxValue)]public int MaxValue{get{return(int)base["maxValue"];}set{base["maxValue"] = value;}}[ConfigurationProperty("minValue",IsRequired=false,DefaultValue=1)]public int MinValue{get { return (int) base["minValue"];}set { base["minValue"] = value; }}[ConfigurationProperty("enabled",IsRequired=false,DefaultValue=true)]public bool Enable{get{return (bool)base["enabled"];}set{base["enabled"] = value;}}}这样子一个简单的配置类就完成了,怎么在程序中使用这个配置呢?需要使用ConfigurationManager类(要引用System.configuration.dll这个dll只有在.Net2.0之后的版本中才有)的GetSection方法获得配置就可以了。
如下代码:SimpleSection simple = ConfigurationManager.GetSection("simple") as SimpleSection; Console.WriteLine("simple minValue={0} maxValue = {1}",simple.MinValue,simple.MaxValue);这个配置类太过简陋了,可能有时候我们还需要更复杂的构造,比如在配置类中使用类表示一组数据,下面我们看一个稍微复杂一点的自定义配置<?xml version="1.0" encoding="utf-8" ?><configuration><configSections><section name="complex" type="plexSection,ConfigExample"/></configSections><complex height="190"><child firstName="James" lastName="Bond"/></complex></configuration>这个配置的名字是complex,他有一个属性height,他的节点内还有一个child元素这个元素有两个属性firstName和lastName;对于这个内嵌的节点该如何实现呢?首先我们需要定义一个类,要从ConfigurationElement类继承,然后再用和SimpleSection类似的方法定义一些用ConfigurationProperty特性修饰的属性就可以了,当然属性值的get,set也要使用基类的索引器。
如下实现:public class ComplexSection : ConfigurationSection{[ConfigurationProperty("height", IsRequired = true)]public int Height{get{return (int)base["height"];}set{base["height"] = value;}}[ConfigurationProperty("child", IsDefaultCollection = false)]public ChildSection Child{get{return (ChildSection)base["child"];}set{base["child"] = value;}}}public class ChildSection : ConfigurationElement{[ConfigurationProperty("firstName", IsRequired = true, IsKey = true)] public string FirstName{get{return (string)base["firstName"];}set{base["firstName"] = value;}}[ConfigurationProperty("lastName", IsRequired = true)]public string LastName{get{return (string)base["lastName"];}set{base["lastName"] = value;}}}还有稍微再复杂一点的情况,我们可能要在配置中配置一组相同类型的节点,也就是一组节点的集合。
如下面的配置:<?xml version="1.0" encoding="utf-8" ?><configuration><configSections><section name="complex" type="plexSection,ConfigExample"/></configSections><complex height="190"><child firstName="James" lastName="Bond"/><children><add firstName="Zhao" lastName="yukai"/><add firstName="Lee" lastName="yukai"/><remove firstName="Zhao"/></children></complex></configuration>请看children节点,它就是一个集合类,在它里面定义了一组add元素,也可以有remove 节点把已经添进去的配置去掉。
要使用自定义节点集合需要从ConfigurationElementCollection类继承一个自定义类,然后要实现此类GetElementKey(ConfigurationElement element)和ConfigurationElement CreateNewElement()两个方法;为了方便的访问子节点可以在这个类里面定义只读的索引器。
请看下面的实现public class Children : ConfigurationElementCollection{protected override object GetElementKey(ConfigurationElement element){return ((ChildSection)element).FirstName;}protected override ConfigurationElement CreateNewElement(){return new ChildSection();}public ChildSection this[int i]{get{return (ChildSection)base.BaseGet(i);}}public ChildSection this[string key]{get{return (ChildSection)base.BaseGet(key);}}}当然要使用此集合类我们必须在Complex类中添加一个此集合类的属性,并要指定集合类的元素类型等属性,如下:[ConfigurationProperty("children", IsDefaultCollection = false)][ConfigurationCollection(typeof(ChildSection), CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap, RemoveItemName = "remove")] public Children Children{get{return (Children)base["children"];}set{base["children"] = value;}}我们会经常用到类似appSettings配置节的键值对的构造,这时候我们就不必再自己实现了,我们可以直接使用现有的ValueConfigurationCollection类来定义一个自定义的键值对。