web.config 隨著專案增長易變得龐大難維護。ASP.NET 提供 configSource 屬性,可將特定區段 (如 connectionStrings、appSettings) 抽離至外部獨立檔案,達到環境隔離、版控安全、部署彈性的效果。本文詳細說明語法、限制、讀取方式與遷移實務。
主 web.config:
<configuration>
<connectionStrings configSource="Config\ConnectionStrings.config" />
<appSettings configSource="Config\AppSettings.config" />
</configuration>
外部檔 Config\ConnectionStrings.config (根節點必須同名):
<connectionStrings>
<add name="Default" connectionString="Data Source=.;Initial Catalog=MyDb;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="Reporting" connectionString="Data Source=ReportSrv;Initial Catalog=RptDb;User Id=reader;Password=***" providerName="System.Data.SqlClient" />
</connectionStrings>
configSource 後,主 web.config 同區段下的子元素**完全失效**,即使保留也不會被讀取。<connectionStrings>、<appSettings>),否則拋出配置錯誤。connectionStrings 與 appSettings 不能同指 Common.config)。外部化對程式碼透明,原有 API 照常運作:
// 連線字串
string conn = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
// appSettings
string uploadPath = ConfigurationManager.AppSettings["UploadPath"];
// 取得整個區段物件 (進階用法)
var section = (ConnectionStringsSection)ConfigurationManager.GetSection("connectionStrings");
web.config 與 Config\*.config.template。ConnectionStrings.config,含機敏密碼,不入版控。連線字串、API Key、第三方密鑰放入外部檔,搭配檔案系統 ACL 僅允許應用程式身分讀取,降低洩漏風險。
多個 IIS 應用程式指向同一組外部配置檔 (放在共享資料夾),修改一處即生效所有站點。
Config 資料夾,設定 IIS_IUSRS 讀取權限。connectionStrings、appSettings 區段內容剪貼至對應外部檔,根節點保持同名。web.config 加入 configSource 屬性,移除原子元素。ConfigurationManager 正常讀取。envsubst、sed、PowerShell 或 Octopus/ Azure DevOps 變數替換)。.gitignore,僅保留 .template 範本。<configSections>
<section name="MyCustomSection" type="MyApp.Config.MySectionHandler, MyApp" />
</configSections>
<MyCustomSection configSource="Config\MyCustom.config" />
善用 configSource 讓 web.config 保持精簡、環境差異外部化,是 ASP.NET 專案邁向專業部署流程的關鍵一步。