子目录使用独立Web.config的配置方法

配置子目录Web.config使其消除继承,用虚拟目录创建多个网站的方法

假设根目录的Web.config设置了一个名为BlogEngine的连接字符串,要在子目录使用另一个名字为BlogEngine的连接字符串,就需要先清除已有的连接字符串(根目录继承下来的connectionString设置),清除所有的配置,可以用clear语法,清除指定名称的配置,可以用remove语法,如下

<--根目录的Web.config-->
<connectionStrings>
  <add name="BlogEngine" connectionString="Data Source=localhost\SQLEXPRESS; Initial Catalog=BlogEngine1; User ID=xxx; Password=xxx" providerName="System.Data.SqlClient"/>
</connectionStrings>
<--子目录的Web.config(clear方法)-->
<connectionStrings>
  <clear/>
  <add name="BlogEngine" connectionString="Data Source=localhost\SQLEXPRESS; Initial Catalog=BlogEngine2; User ID=xxx; Password=xxx" providerName="System.Data.SqlClient"/>
</connectionStrings>
<--子目录的Web.config(remove方法)-->
<connectionStrings>
  <remove name="BlogEngine"/>
  <add name="BlogEngine" connectionString="Data Source=localhost\SQLEXPRESS; Initial Catalog=BlogEngine2; User ID=xxx; Password=xxx" providerName="System.Data.SqlClient"/>
</connectionStrings>

这里只是用connectionString为例,使用时完全可以应用在所有可以配置的节点上,任何配置节点都可以用clear和remove节点将继承来的配置先清除掉,然后再add新的配置。此方法灵活性更强,同时可以保留根目录Web.config中的部分共同配置(而无需全部重新设定)。下面是一个复杂些的例子,分别是根目录和子目录在system.webServer上的配置。

<--根目录的Web.config system.webServer配置节点-->
<modules>
  <remove name="ScriptModule"/>
  <add name="WwwSubDomainModule" type="BlogEngine.Core.Web.HttpModules.WwwSubDomainModule, BlogEngine.Core"/>
  <add name="UrlRewrite" type="BlogEngine.Core.Web.HttpModules.UrlRewrite, BlogEngine.Core"/>
  <add name="CompressionModule" type="BlogEngine.Core.Web.HttpModules.CompressionModule, BlogEngine.Core"/>
  <add name="ReferrerModule" type="BlogEngine.Core.Web.HttpModules.ReferrerModule, BlogEngine.Core"/>
  <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<--子目录的Web.config system.webServer配置节点-->
<modules runAllManagedModulesForAllRequests="true">
  <remove name="WwwSubDomainModule"/>
  <remove name="UrlRewrite"/>
  <remove name="CompressionModule"/>
  <remove name="ReferrerModule"/>
  <remove name="ScriptModule"/>
  <add name="UrlRewrite" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
  <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>

可以看到,子目录将所有根目录定义的Modules(WwwSubDomainModule,UrlRewrite,CompressionModule,ReferrerModule,ScriptModule)都清除了,添加了自己的UrlRewrite和ScriptModule两个Module。如此配置既消除了冲突,又可以实现了配置的部分继承(子目录只有部分配置和根目录不同),而第一种方法却无法实现部分继承。

总结

了解了Web.config的继承方式和子目录的配置方法,我们就能够很轻松的运用子目录建立一个独立于父目录的全新网站,使用完全不同的数据库和连接字符串,完全不同的Module,完全不同的HttpHandler,实在是一件很爽的事情。以Godaddy为例,将域名绑定到Godaddy的子目录,修改子目录的Web.config使其不予根目录的配置冲突,一个新的网站就上线了!

 

作者:tactk,版权所有,如若转载,请注明出处:https://www.tacgeek.com/500.html

(1)
tactk的头像tactk
上一篇 2018-02-01
下一篇 2017-12-29

相关推荐

发表回复

登录后才能评论
企业微信
跳至工具栏