li.的博客
li.的首页 > li.的博客 > 浏览文章

在asp.net 2.0中的web.config文件中调用外部文件

分类:.net应用  人气:1765  评论:0  时间:2011-02-09 14:45

直接看例子代码:
===============================

在一个工作项目或者工作小组中,有可能经常要转换工作的调试环境,比如开发环境,测试环境,部署环境,这样有可能要对web.config文件进行修改或改动,比如要改数据库的连接字符串,角色配置,安全配置环境等,一不小心,很容易会发生遗漏等错误.在asp.net 2.0的web.config文件中,新加入了可以引入外部文件的新特性,
使到我们可以先预先搞好几个文件,比如将经常要改动的部分,如数据库连接串部分等,按不同的开发环境,分别写成若干个xml文件,然后在web.config中把它们按需要调入进来.比如

我们先建立两个目录,一个叫test,一个叫developer,分别存放测试和开发时,用到的不同环境,比如
在devloper文件中建立一个developerconnectionstring.xml,内容如下

<connectionStrings>
<add name="connstr" connectionString=
"data source=.\sqlexpress;initial catalog=
northwind;integrated security=true"
providerName="System.Data.SqlClient"/>
</connectionStrings>再建立一个developerappsetingstring.xml如下<appSettings><add key="autoemail" value="abc@abc.com /> </appSettings>

再建立一个developermembership.xml如下

<membership defaultProvider="Northwind">
<providers>
<add name="Northwind"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="connstr"/>
</providers>
</membership>同样道理,可以在test目录下,也建立相关类似的xml文件,然后,在web.config中,可以这样调用了
<?xml version="1.0"?>
<configuration>
<appSettings configSource="developer\developerappsetingstring.xml"/>
<connectionStrings
configSource="developer\developerconnectionstring.xml" />
<system.web>
<membership
configSource="developer\developermembership.xml"/>
<compilation debug="true"/>
<authentication mode="Forms"/>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>
可以看到,在web.config中,可以通过configsource属性来读取外部文件

================================

比如 外部文件ext_appSettings.xml内容:

<appSettings><add key="Test1" value="1" /></appSettings>

web.config中的appSettings可以修改成<appSettings configSource="ext_appSettings.xml" />,注意,这样的话web.config中的appSettings内不能包含任何内容了,这有利于多人多环境的开发。

=========================

我用伪静态做了一个项目,在web.config里加了
<CustomConfiguration>
  <urls> 
  <add virtualUrl="~/Index/index.html" destinationUrl="~/Index/index.aspx"/>
  <add virtualUrl="~/products/productslist.html" destinationUrl="~/products/productslist.aspx"/>
  </urls>
 </CustomConfiguration>
如果我每个页都加的话,web.config里面的代码太多了,所以,我想用一个文件存这些代码,请问该怎么加啊,加在一个什么文件里,并且如何读它们,请给出一个详细的方案

方案:
web.config节点引用外部config文件。很容易的,你只需要把<CustomConfiguration>以及它的子节点全都保存在另外一个config文件里,比如customConfiguration.config。然后将web.config里
<CustomConfiguration>...</CustomConfiguration>改写为
<CustomConfiguration configSource="customConfiguration.config" />

评论(0)
暂无评论
我来评论
(800字以内)