2016-12-01 148 views
1

我有一個Web.config文件,其中有一些條目,但取決於當我執行我的Web應用程序時處於調試模式還是發佈模式本地,我想採取不同的appSettings。Web.Debug.config與Web.Release.config在本地主機上運行web應用程序

例如,假設我的Web.Debug.config appSettings中有以下條目。

<add key="MyServiceUrl" value="http://my-test-site:8080/" /> 

而且我也有這個在我的Web.Release.config:

<add key="MyServiceUrl" value="http://my-prod-site:80/" /> 

我應該如何配置我的web.config,Web.Debug.Config和Web.Release.Config所以根據模式我在本地運行我的應用程序(調試 - 任何CPU發佈 - 任何CPU),它採取正確的?

現在,無論我在Visual Studio中選擇調試還是發佈,唯一需要的鍵和值對都來自主Web.Config。

如何配置該行爲?

編輯

這是我如何定義的Web.config

<appSettings> 
    <add key="webpages:Enabled" value="false" /> 
    <add key="ClientValidationEnabled" value="true" /> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true" /> 
</appSettings> 

這是我如何定義Web.Debug.config

<appSettings> 
    <add key="MyServiceUrl" value="http://my-test-site:8080/" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/> 
</appSettings> 

這是我怎麼有定義的Web.Release.config

<appSettings> 
    <add key="MyServiceUrl" value="http://my-prod-site:8080/" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" /> 
</appSettings> 

最後,在我的代碼,我有以下方法:

public static string GetAppSetting(string settingKey) 
     { 
      if (string.IsNullOrEmpty(settingKey)) 
       throw new System.ArgumentException("Cannot fetch a setting for a null/empty setting key."); 
      return ConfigurationManager.AppSettings[settingKey]; 
     } 

我稱之爲它是這樣的: 串設定= GetAppSetting( 「MyServiceUrl」);

然而,這是空如果不是在主Web.config中

+0

請將_

+0

或使用:_xdt:Transform =「Insert」_ –

回答

1

在web.Release.config試試這個定義的,它應該工作:

<appSettings> 
<add key="MyServiceUrl" value="http://my-prod-site:8080/" xdt:Transform="Insert" /> 
</appSettings> 

閱讀:Web.config Transformation Syntax for Web Application Project Deployment

+0

不幸的是,確切的情況會發生。如果條目不存在於web.config中,則在我調用GetAppSetting時,沒有任何條目會填充。並且...如果它存在,它將採用它在主web.config中的所有內容,而不是從調試版或發行版中取出。 – user3587624

+0

如果刪除** static **,該怎麼辦? from:_public static string GetAppSetting(string settingKey)_ –

+0

這是一回事。它從主web.config – user3587624

相關問題