2013-05-14 63 views
0

我正在開發一個ASP.NET項目,我需要在我的web-app的appSettings部分添加一些設置。在幾個web.config文件中拆分'appSettings'部分

現在這些設置正在成長,所以我想組織它們在不同的文件中。我創建其他web.config文件中在我的應用程序的不同的目錄,將是這樣的:

<?xml version="1.0"?> 
<configuration> 
    <system.web> 
    </system.web> 
    <appSettings> 
    <add key="settingKey" value="settingValue" /> 
    </appSettings> 
</configuration> 

但是當我嘗試通過ConfigurationManager.AppSettings["settingKey"]訪問他們,我得到null

那麼,是否可以拆分不同文件中的設置?是否有另一種方法來邏輯組織應用程序設置值?

+0

看看這個:http://stackoverflow.com/questions/11363121/connectionstring-management-for-many-projects-on-one-server-should-i-make-my-ow/11363291#11363291 – 2013-05-14 16:35:42

回答

0

如果當前執行的路徑位於該目錄中,您將只能看到目錄中的web.config設置。

因此,例如: /MyDirectory/web.config

纔可見如果您在加載頁面,如: /Mydirectory/MyTestPage.aspx

你不會看到web.config設置在此例如: /OtherDirectory/MyTestPage.aspx

這篇文章可能會有幫助: Creating a custom .config file in asp.net

0

我知道這我s太舊了,可能甚至不適用於.NET Core,但對於那些來自Google並使用非.NET Core json配置文件的應用程序。以下是我通常所做的...

我使用configSourcesweb.config中取出所有配置設置。這可以讓你到一個特定的配置節到不同的文件例如通過提供相對位置這裏是如何你會在聲明配置節一configSource(根web.config文件)...

<configuration> 

    <log4net configSource="Config\debug\log4net.config" /> 
    <appSettings configSource="config\debug\settings.config" /> 
    <connectionStrings configSource="config\debug\connections.config" />  
    ...  
</configuration> 

你可以只要確定指定的路徑和文件存在於解決方案中,就可以命名這些文件。下面介紹一下的settings.config文件看起來像......

<?xml version="1.0"?> 
<appSettings> 
    <add key="webpages:Version" value="3.0.0.0" /> 
    <add key="webpages:Enabled" value="false" /> 
    <add key="ClientValidationEnabled" value="true" /> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true" /> 
    <add key="foo" value="bar" /> 
</appSettings> 

現在,相對路徑是相對於項目的根......

enter image description here

在上圖中可以看到,我爲不同的部署環境提供了兩條不同的路徑,這是因爲顯然我的連接字符串和設置在生產中是不同的。

然後你可以使用配置的轉換,使應用程序能夠使用正確的配置文件,無論是在調試或發行模式...

enter image description here

這就是Web.Debug.config文件的樣子..

<?xml version="1.0"?> 
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> 
    <log4net configSource="Config\debug\log4net.config" xdt:Transform="Replace" /> 
    <appSettings configSource="config\debug\settings.config" xdt:Transform="Replace" /> 
    <connectionStrings configSource="config\debug\connections.config" xdt:Transform="Replace" /> 
</configuration> 

發行版本幾乎是一樣的...替換提供給configSource屬性的路徑。這就是它。 還有其他web.config元素支持configSource設置,例如很多system.serviceModel子元素。