2010-03-09 87 views
18

我必須在WCF主機使用的web.config文件和Web客戶端使用的web.config文件之間複製一些設置(如連接字符串)。可以從外部xml文件讀取web.config文件嗎?

爲了不重複,我可以同時從單獨的xml文件讀取web.configs嗎?這兩個web.configs可以完全在不同的解決方案/項目中,所以我猜這是不可能的,但想得到其他人的意見。 PS:我明白我可以使用數據庫來存儲所有的配置設置。

回答

19

是的,任何配置部分可以是「外部化」 - 這包括像<appSettings><connectionStrings>和更多。

你最好有這樣的事情在你的web.config:

<configuration> 
    <appSettings configSource="appSettings.config" /> 
    <connectionStrings configSource="connectionStrings.config" /> 
    <system.web>  
     <pages configSource="pages.config" /> 
     <httpHandlers configSource="httphandlers.config"> 
    </system.web>  
</configuration> 

外向配置的也只是包含在其中一個小節:

httphandlers.config:

<httpHandlers> 
    <remove verb="*" path="*.asmx"/> 
    <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 
    <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 
    <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/> 
</httpHandlers> 

請注意,您不能外部化整個<system.web>部分,因爲這是一個配置節組 - 不是配置部分 - 但您可以將system.web中包含的大部分子部分外部化。

+0

httphandlers.config位於何處?共享此配置文件的項目可能位於域 – DotnetDude

+0

@DotnetDude:如果您未指定路徑,httpHandlers.config必須與web.config位於同一位置。您可以指定子路徑,例如configSource =「config \ httpHandlers.config」將所有的配置文件放在一個地方。要在多個項目之間共享,要麼複製到不同的項目位置,要麼在操作系統級別上做符號鏈接等操作,以便在各個目錄位置顯示一個物理文件 –

1

如果可以,只需將配置在Machine.Config中相同即可。他們都可以從那裏讀取,並且每個web.config都可以覆蓋您需要的任何值。

我說如果可以的話,因爲我知道許多託管公司不會讓你修改它,除非你租用專用服務器。

11

只要文件位於相同路徑(包括子目錄)中,配置文件就可以指向其他配置文件。

這裏是我的配置設置的示例:

<connectionStrings configSource="web\config\connectionStrings.config" /> 
<appSettings configSource="web\config\appSettings.config" /> 
<system.diagnostics configSource="web\config\diagnostics.config" /> 
<system.serviceModel> 
    <bindings configSource="web\config\serviceModelBindings.config" /> 
    <behaviors configSource="web\config\serviceModelBehaviors.config" /> 
    <services configSource="web\config\serviceModelServices.config" /> 
    <client configSource="web\config\serviceModelClient.config" /> 
</system.serviceModel> 

就我而言,我有一個根文件夾,其中包括Web應用程序的子文件夾中的幾個Windows應用程序。這允許每個應用程序的配置文件指向共享配置。

+0

** runtime **和** system.web.extensions * * _sections_不適用於*** configSource ***? – Kiquenet