首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 2.0 web.config 透過 configSource 引入外部配置檔

     編輯:關於ASP.NET

專案常在開發/測試/正式環境切換,連接字串、角色、安全設定頻繁變動。ASP.NET 2.0 `configSource` 屬性讓 `web.config` 保持乾淨,環境差異抽離到外部 XML 檔。

目錄結構

/Config/Developer/connectionStrings.xml
/Config/Developer/appSettings.xml
/Config/Developer/membership.xml
/Config/Test/connectionStrings.xml
...

外部配置檔範例

<!-- connectionStrings.xml -->
<connectionStrings>
  <add name="Conn" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DevDB;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

<!-- appSettings.xml -->
<appSettings>
  <add key="AdminEmail" value="admin@dev.local" />
</appSettings>

<!-- membership.xml -->
<membership defaultProvider="DevProvider">
  <providers>
    <add name="DevProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="Conn" />
  </providers>
</membership>

web.config 引用

<configuration>
  <appSettings configSource="Config/Developer/appSettings.xml" />
  <connectionStrings configSource="Config/Developer/connectionStrings.xml" />
  <system.web>
    <membership configSource="Config/Developer/membership.xml" />
    <compilation debug="true" />
    <authentication mode="Forms" />
  </system.web>
</configuration>

切換環境

修改 `web.config` 中的路徑前綴(`Developer` → `Test`),或透過建置事件/部署腳本自動替換,實現**零代碼變更**切換環境。

限制與注意

  • 外部檔案**必須只包含對應區段的根元素**(如 `...`),不能有 `` 包裹。
  • 修改外部檔案**不會自動重啟應用程式**,需觸碰 `web.config` 或回收應用程式池生效。
  • 支援區段:`appSettings`、`connectionStrings`、所有 `system.web` 子區段(`membership`、`roleManager`、`pages` 等)。

此特性讓配置管理更符合「配置與代碼分離」原則,極大降低部署出錯風險。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved