解决在Web.config或App.config中添加自定义配置的方法详解

合集下载

ASP NET自定义配置文件设置(以及修改Entity Framework数据库连接为自定义字符串)

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节点

在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一个配置文件解决方法(其他配置文件引入方式)

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文件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使用方法指南

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详解

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配置文件详解(二)

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.config配置文件详解(新手必看)

Web.c‎o nfig‎配置文件详‎解(新手必‎看)‎花了点时间‎整理了一下‎A SP.N‎E T We‎b.con‎f ig配置‎文件的基本‎使用方法。

‎很适合新手‎参看,由于‎W eb.c‎o nfig‎在使用很灵‎活,可以自‎定义一些节‎点。

所以这‎里只介绍一‎些比较常用‎的节点。

‎<?xm‎l ver‎s ion=‎"1.0"‎?><‎!--注意‎:除了手‎动编辑此文‎件以外,您‎还可以使用‎Web ‎管理工具来‎配置应用程‎序的设置。

‎可以使用‎V isua‎l Stu‎d io 中‎的“网站”‎->“As‎‎配置”选‎项。

设‎置和注释的‎完整列表在‎mach‎i ne.c‎o nfig‎.comm‎e nts ‎中,该文件‎通常位于‎"Wind‎o ws"M‎i cros‎o ft.N‎e t"Fr‎a mewo‎r k"v2‎.x"Co‎n fig ‎中。

-->‎<!‎--Web‎c onfi‎g文件是一‎个xml文‎件,con‎f igur‎a tion‎是xml文‎件的根节点‎,由于xm‎l 文件的根‎节点只能有‎一个,所以‎W ebco‎n fig的‎所有配置都‎是在这个节‎点内进行的‎。

-->‎<con‎f igur‎a tion‎>‎<!--指‎定配置节和‎命名空间声‎明。

cle‎a r:移除‎对继承的节‎和节组的所‎有引用,只‎允许由当前‎sect‎i on 和‎sect‎i onGr‎o up 元‎素添加的节‎和节组。

r‎e move‎:移除对继‎承的节和节‎组的引用。

‎se‎c tion‎:定义配置‎节处理程序‎与配置元素‎之间的关联‎。

sect‎i onGr‎o up:定‎义配置节处‎理程序与配‎置节之间的‎关联。

--‎><‎c onfi‎g Sect‎i ons>‎‎<sec‎t ionG‎r oup ‎n ame=‎"syst‎e m.we‎b.ext‎e nsio‎n s"t‎y pe="‎S yste‎m.Web‎.Conf‎i gura‎t ion.‎S yste‎m WebE‎x tens‎i onsS‎e ctio‎n Grou‎p,Sy‎s tem.‎W eb.E‎x tens‎i ons,‎Vers‎i on=1‎.0.61‎025.0‎, Cul‎t ure=‎n eutr‎a l,P‎u blic‎K eyTo‎k en=3‎1bf38‎56ad3‎64e35‎">‎‎<sect‎i onGr‎o up n‎a me="‎s crip‎t ing"‎type‎="Sys‎t em.W‎e b.Co‎n figu‎r atio‎n.Scr‎i ptin‎g Sect‎i onGr‎o up, ‎S yste‎m.Web‎.Exte‎n sion‎s,Ve‎r sion‎=1.0.‎61025‎.0, C‎u ltur‎e=neu‎t ral,‎Publ‎i cKey‎T oken‎=31bf‎3856a‎d364e‎35">‎‎ <‎s ecti‎o n na‎m e="s‎c ript‎R esou‎r ceHa‎n dler‎"typ‎e="Sy‎s tem.‎W eb.C‎o nfig‎u rati‎o n.Sc‎r ipti‎n gScr‎i ptRe‎s ourc‎e Hand‎l erSe‎c tion‎,Sys‎t em.W‎e b.Ex‎t ensi‎o ns, ‎V ersi‎o n=1.‎0.610‎25.0,‎Cult‎u re=n‎e utra‎l,Pu‎b licK‎e yTok‎e n=31‎b f385‎6ad36‎4e35"‎requ‎i rePe‎r miss‎i on="‎f alse‎"all‎o wDef‎i niti‎o n="M‎a chin‎e ToAp‎p lica‎t ion"‎/>‎‎</sec‎t ionG‎r oup>‎‎</se‎c tion‎G roup‎>‎ <se‎c tion‎name‎="rew‎r iter‎"typ‎e="In‎t elli‎g enci‎a.Url‎R ewri‎t er.C‎o nfig‎u rati‎o n.Re‎w rite‎r Conf‎i gura‎t ionS‎e ctio‎n Hand‎l er, ‎I nt el‎l igen‎c ia.U‎r lRew‎r iter‎" />‎</c‎o nfig‎S ecti‎o ns>‎‎<!--a‎p pSet‎t ings‎是应用程序‎设置,可以‎定义应用程‎序的全局常‎量设置等信‎息-->‎‎<app‎S etti‎n gs>‎<ad‎d key‎="1" ‎v alue‎="1" ‎/>‎<add ‎k ey="‎g ao" ‎v alue‎="wei‎p eng"‎/>‎</ap‎p Sett‎i ngs>‎‎<!--‎连接字符串‎设置-->‎<c‎o nnec‎t ionS‎t ring‎s>‎ <a‎d d na‎m e="C‎o nnSt‎r ing"‎conn‎e ctio‎n Stri‎n g="D‎a ta S‎o urce‎=GAO;‎I niti‎a lCa‎t alog‎=HBWX‎D ate;‎U ser ‎I D=sa‎;pass‎w ord=‎s a"><‎/add>‎‎<add‎name‎="111‎" con‎n ecti‎o nStr‎i ng="‎11111‎" />‎</c‎o nnec‎t ionS‎t ring‎s>‎<!‎--指定应‎用子配置设‎置的资源,‎并锁定配置‎设置,以防‎止它们被子‎配置文件重‎写。

在C#类库中使用App.config文件自定义配置

在C#类库中使用App.config文件自定义配置

在C#类库中使⽤App.config⽂件⾃定义配置 做项⽬时,经常需要在⾃⼰设计的类库中使⽤很多⽤户配置。

虽然在应⽤程序的App.config和Web应⽤程序web.config这样的⽂件⾥配置也能满⾜需求,但这样做不仅会让主配置⽂件的内容变得多、杂,还会让模块依赖主程序的配置⽂件。

我们知道在VS中,可以在类库项⽬⾥添加⼀种叫做“应⽤程序配置⽂件”的⽂件,这是标准的.NET配置⽂件,模板⾃带“configuration”元素,编辑时还会有智能提⽰。

但是怎么在程序代码中使⽤写在App.config⾥的配置呢?近⽇在⽹上搜了⼀通,却⼀⽆所获。

于是只好⾃已动⼿! 我以前做的⼀个项⽬⾥,⽤到过类型的实现⽅式。

可以获取在类库App.config⽂件中“appSettings”和“conectionStrings”节添加的⾃定义配置,但是不能⾃定义配置节。

从MSDN上了解到,要想在配置⽂件中⾃定义配置节,需要实现⼀个⾃定义的ConfigurationSection。

两下结合起来,想在类库中⽤App.config彻底⾃定义配置的需求就可以实现了。

现在分享出来,希望对看到这篇⽂章的朋友有所帮助。

第⼀步:创建项⽬和类库: 新建⼀个Windows控制台应⽤程序“MyDemo”,然后再新建⼀个C#类库“MyDemo.Config”,并在MyDemo中添加对MyDemo.Config的引⽤。

第⼆步:添加引⽤,新建配置⽂件: 在MyDemo.Config中先删除除System之外的所有引⽤,然后添加对System.Configuration库的引⽤,并新建⼀个配置⽂件App.config。

第三步:在MyDemo.Config⾥⾯添加⼀个静态类“ConfigManager”,代码⾥这样写:View Codeusing System;using System.Configuration;namespace MyDemo.Config{public static class ConfigManager{readonly static bool _Error;static Configuration _AppConfig;static ConfigManager(){string dllPath = string.Format("{0}\\{1}.dll", AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory, "MyDemo.Config");try{_AppConfig = ConfigurationManager.OpenExeConfiguration(dllPath);}catch(ConfigurationErrorsException){_Error = true;}}public static KeyValueConfigurationCollection AppSettings{get{if (_Error) return null;return _AppConfig.AppSettings.Settings;}}public static ConnectionStringSettingsCollection ConnectionStrings{get{if (_Error) return null;return _AppConfig.ConnectionStrings.ConnectionStrings;}}}} 通过AppDomain.CurrentDomain.BaseDirectory和稳定的类库名称,来获取实际运⾏中该dll⽂件的具体物理路径,然后通过ConfigurationManager的OpenExeConfiguration⽅法就能获取到相应的dll.config⽂件中的配置。

一步一步教你玩转.NET Framework的配置文件app.config

一步一步教你玩转.NET Framework的配置文件app.config

一步一步教你玩转.NET Framework的配置文件app.config在一般的项目中,为了使你的代码更加灵活,更方便调整,减少不必要的hard code,我们都在config中添加许多配置信息,一般可以选择.NET自带的配置文件形式app.config或者web 项目中的web.config来完成配置工作。

.NET中提供了几个和配置有关的类来支持用完轻松的完成配置文件的读写设置:System.Configuration.ConfigurationSectionGroup一般和你项目中使用的Assambly保持1:1的对应关系,这样划分使得结构相对清晰,权责明确。

当然你可以不使用它,这样一旦你的Assambly在别的地方要被重用时,找出相应的config信息就变得很困难。

System.Configuration.ConfigurationSection维护一个相对独立的配置节,使用时需现在<ConfigSections></ConfigSections>节点下声明。

我们熟悉的<appSettings></appSettings>以及<connectionStrings></connectionStrings/>就是.NET为我们预留的一个Section。

System.Configuration.ConfigurationElementCollection &System.Configuration.ConfigurationElement就是Section下具体的配置信息和配置信息的集合了。

下面来看看怎么使用这些类玩转app.config1.初级玩法最初级的用法当然是使用<appSettings/>,我们在app.config 中添加<configuration><appSettings><add key="MyConfigString" value="Test Config Data"/></appSettings></configuration>访问它public class AppSettingConfig{public string resultValue;public AppSettingConfig(){this.resultValue =ConfigurationManager.AppSettings["MyConfigString"].ToString();}}[TestMethod]public void TestAppSettingConfigNode(){AppSettingConfig appCon = new AppSettingConfig();Assert.AreEqual("Test Config Data", appCon.resultValue);}没有问题!我们加个Section来看看如何访问:<configuration><configSections><sectionGroup name="MySectionGroup"><section name="MyFirstSection"type="System.Configuration.DictionarySectionHandler"/><section name="MySecondSection"type="System.Configuration.DictionarySectionHandler"/></sectionGroup></configSections><MySectionGroup><MyFirstSection><add key="First" value="First Section"/></MyFirstSection><MySecondSection><add key="Second" value="Second Section"/></MySecondSection></MySectionGroup></configuration>注意我们在section的type中给出了System.Configuration.DictionarySectionHandler,这也限制了我们在具体的ConfigurationElement中只能使用<add key=”” value=””/>的形式,使得我们GetSection()方法返回的是一个IDictory对象,我们可以根据Key来取得相应的值public class SectionConfig{public string resultValue;public SectionConfig(){System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None );IDictionary dic =ConfigurationManager.GetSection("MySectionGroup/MySecondSection") as IDictionary;this.resultValue = dic["Second"].ToString();}}[TestMethod]public void TestSectionGroupConfigNode(){SectionConfig sc = new SectionConfig();Assert.AreEqual("First Section", sc.resultValue);}还是没问题。

解决在Web.config或App.config中添加自定义配置的方法详解

解决在Web.config或App.config中添加自定义配置的方法详解

解决在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方法获得配置就可以了。

web.config配置说明

web.config配置说明

web.config配置说明<configuration>//顶层元素<system.web>//⼤多应⽤程序设置位于此元素下<sessionState mode='Inproc' timeout='10' />//设置会话状态超时时间</system.web></configuration>Table 3-1.可⽤于web.config的顶层配置元素元素Element含义Purpose<authentication>指定所使⽤的客户⾝份验证模式Specify the client authentication mode to use<authorization>允许或者拒绝⽤户或⾓⾊的访问Allow or deny users or roles access<browserCaps>根据⽤户代理指定浏览器的能⼒Specify browser capabilities based on user agent<clientTarget>定义客户⽬标Define client targets<compilation>控制同页编译和程序集引⽤Control page compilation and assembly references<customErrors>控制错误页显⽰和定义⾃定义的错误页Control error page display and define custom error pages<globalization>设置请求和响应的编码Set the request and response encoding<httpHandlers>添加或移除HTTP处理程序Add or remove HTTP handlers<httpModules>添加或移除HTTP模块Add or remove HTTP modules<httpRuntime>控制HTTP请求的处理Control aspects of HTTP request processing<identity>为该应⽤程序指定标识Specify impersonation for this application<machineKey>控制验证和解密的钥匙Control the validation and decryption key<pages>设置全局的⽹页默认属性Set defaults for page attributes globally<processModel>控制⼯作者进程的⾏为⽅式Control the behavior of the worker process<securityPolicy>使⽤相关的策略⽂件定义信任等级Define trust levels with associated policy files<sessionState>控制会话状态Control session state<trace>启⽤应⽤程序范围的跟踪Enable application-wide tracing<trust>选择使⽤的信任等级Select which trust level to use<webServices>指定Web服务的协议和范围Specify Web service protocols and extensions<appSettings>添加应⽤程序专⽤的数据元素Add application-specific data elements1, 配置的四个层次(1)机器:machine.config:位于$FRAMEWORK\CONFIG($FRAMEWORK⼀般是c:\winnt\\Framework\v1.0.3705),是.net必须备的默认配置⽂件。

web.config配置详细说明

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>定义了⼀个错误重定向页⾯.III.<appSettings configSource="source/new.xml"/>可以通过新的XML来扩展配置内容。

new.xml写法为:<?xml version="1.0" encoding="utf-8" ?><appSettings><add key="" value="|"/></appSettings>3.<compilation>节格式:<compilation defaultLanguage="c#" debug="true" />I.default language: 定义后台代码语⾔,可以选择C#和两种语⾔.II.debug : 为true时,启动aspx调试;为false不启动aspx调试,因⽽可以提⾼应⽤程序运⾏时的性能。

web.config详解(配置文件节点说明)

web.config详解(配置文件节点说明)

web.config详解(配置文件节点说明)Posted on 2009-02-15 20:50 Charles Chen阅读(625) 评论(0)编辑收藏所属分类: Web.config深入浅出, web.config文件是一个XML文件,它的根结点是<configuration>,在<configuration>节点下的常见子节点有:<configSections>、<appSettings>、<connectionStrings>和<system.web>。

其中<appSettings>节点主要用于配置一些网站的应用配置信息,而<connectionStrings>节点主要用于配置网站的数据库连接字符串信息。

<system.web>节点主要是网站运行时的一些配置,它的常见节点有如下:1.<appSettings>节点<appSettings>节点主要用来存储应用程序的一些配置信息2.<compilation>节点<compilation>节点配置 使用的所有编译设置。

默认的debug属性为“true”,即允许调试,在这种情况下会影响网站的性能,所以在程序编译完成交付使用之后应将其设为“false”。

3.<authentication>节点设置身份验证模式,有四种身份验证模式,它们的值分别如下:Mode 说明Windows 使用Windows身份验证,适用于域用户或者局域网用户。

Forms 使用表单验证,依靠网站开发人员进行身份验证。

Passport 使用微软提供的身份验证服务进行身份验证。

None 不进行任何身份验证。

4.<customErrors>节点<customErrors>节点用于定义一些自定义错误信息的信息。

对Web.config配置文件的常见操作-洞幺人生-博客园

对Web.config配置文件的常见操作-洞幺人生-博客园

对Web.config配置⽂件的常见操作-洞⼳⼈⽣-博客园对Web.config配置⽂件的常见操作对于配置⽂件的常见操作包括:l 读取l 修改l 将web.config中的配置节放在单独的⽂件中l 对某⼀节进⾏加密l 添加定制的节操作web配置⽂件(包括machine.config和web.config等)的命名空间是:System.Web.Configuration。

主要应⽤的类是:WebConfigurationManager。

下⾯看看WebConfigurationManager类的成员。

(可以利⽤MSDN来查看,我下⾯是利⽤Lutz Roeder的Reflector)图 1 WebConfigurationManager类成员3.2.1 读取图 2 WebConfigurationManager类中⽤于读取的属性和⽅法3.2.1.1 读取appSettings节和connectionStrings节在WebConfigurationManager类中,我们⾸先注意到其两个属性AppSettings和ConnectionStrings。

这两个属性就是⽤于操作我们前⾯看到的web.config⽂件中的两节appSettings和connectionStrings。

下⾯演⽰使⽤⽅法。

演⽰操作appSettings 节的代码:using System.Web.Configuration;....string message;message = WebConfigurationManager.AppSettings["message"];...演⽰操作connectionStrings节的代码:using System.Web.Configuration;....string connectionString =WebConfigurationManager.ConnectionStrings["pubs"].ConnectionString;...3.2.1.2 读取其它节在.NET中读取其它节要⿇烦⼀些。

图解修改IISweb.config配置文件增设置默认文档的方法

图解修改IISweb.config配置文件增设置默认文档的方法

图解修改IISweb.config配置⽂件增设置默认⽂档的⽅法我们在发布的⽹站中找到web.config⽂件,打开这个这件,在<configuration></configuration>标签内添加⼏段代码,就可以指定默认启动的页⾯了。

<system.webServer>复制代码代码如下:<defaultDocument><files><add value="DreyeOnlineTestPage.html" /></files></defaultDocument></system.webServer>这样我们就不需要⼿动去指定⼀个页⾯作为⽹站的起始页⾯了。

注意:如果你的IIS中存在配置⽂件中指定的页⾯,此时你点击IIS中⽹站下的默认⽂档,就会发⽣错误,如下:这是因为你⽹站中已经存在指定的这个页⾯了,错误原因是IIS中已经设置了默认document为DreyeOnlineTestPage.html,这时候得到了另外⼀个相同value的add引发异常。

所以不能添加相同的值,如果你你建⽴的⽹站的默认⽂档中不存在这个页⾯,那就在IIS的根⽬录下的默认⽂档中找,如图中的红⾊圈:点击红⾊圈所圈的项,然后在右边的功能视图中找到默认⽂档,然后在这个⾥⾯寻找,有没有出现重复的。

当然你可以指定⼀个页⾯,放⼊这个⾥⾯,然后它就会成为所有⽹站的默认起始页⾯。

如果你嫌⿇烦找的话,将配置⽂件中的添加默认⽂档的代码删除就可以了,或者可以使⽤clear清除,然后再添加。

代码如下:<add />之前加⼊<clear />即修改web.config为复制代码代码如下:<system.webServer><defaultDocument><files> <clear/><add value="DreyeOnlineTestPage.html" /></files></defaultDocument></system.webServer>如果不在IIS上修改默认⽂档,⽽直接在config⽂件⾥⾯更改,⼀样会体现在IIS中。

单元测试获取不到配置文件自定义配置的问题解决方法

单元测试获取不到配置文件自定义配置的问题解决方法

单元测试获取不到配置⽂件⾃定义配置的问题解决⽅法
在单元测试时如果需要类似这样的
ConfigurationManager.AppSettings["key"]
获取⾃定义配置信息将会获取不到值。

解决⽅法有三个:
⽅法⼀:
在单元测试项⽬中添加app.config⽂件并且把被测项⽬中⾃定义的配置复制⼀份到这个新增的⽂件中。

缺点:每次都要⼿动同步这两个⽂件。

⽅法⼆:
1、在单元测试项⽬上右键,添加现有项
2、找到被测项⽬的配置⽂件所在路径,如果找不到配置⽂件,注意选择“所有⽂件”,添加⽅式选择“添加为链接”
缺点:如果两个项⽬的配置⽂件命名规则不⼀样还是获取不到,⽐如要测试的是web项⽬他的配置⽂件是web.config
⽅法三:
1、右键单元测试项⽬,选择属性
2、选择⽣成事件,单击“编辑预先⽣成”,添加以下代码,并确定,注意把“Admin.Web”换成你要测试的项⽬名称
copy "$(SolutionDir)Admin.Web\web.config""$(ProjectDir)$(OutDir)$(TargetFileName).config"
缺点:暂未发现。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 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类来定义一个自定义的键值对。

相关文档
最新文档