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

ASP.NET web.config 基礎解析 (一):配置檔層級、搜尋優先序與操作技巧

     編輯:關於ASP.NET

為什麼需要 web.config?

部署時不想公開原始碼,且開發/測試/生產環境設定 (連線字串、服務端點等) 不同。web.config 為 XML 純文字檔,不編譯進 DLL,部署後可直接用記事本修改即時生效,極大簡化維運。

配置檔層級與搜尋優先序

ASP.NET 讀取設定時,依下列順序搜尋,先找到者生效:

  1. 當前頁面目錄下的 web.config
  2. 父目錄 web.config,遞迴至網站根目錄
  3. 系統層級 web.config:`%windir%\Microsoft.NET\Framework\\CONFIG\web.config`
  4. 機器層級 machine.config:同目錄下的 `machine.config`
  5. 皆無 → 回傳 null

此機制支援「設定繼承與覆寫」:根目錄定義通用設定,子目錄僅覆寫差異部分。

主要設定區段分類

區段群組常見區段用途
system.webcompilation, authentication, authorization, customErrors, httpHandlers, httpModules, sessionState, pagesASP.NET 執行階段核心行為
system.webServerhandlers, modules, rewriting, security, staticContentIIS 7+ 整合管線設定
connectionStringsadd (name, connectionString, providerName)資料庫連線字串集中管理
appSettingsadd (key, value)應用程式自訂鍵值對
applicationSettings / userSettings設定檔強型別存取 (Settings 類別)型別安全的設定存取

程式碼操作 web.config

讀取 appSettings

string val = ConfigurationManager.AppSettings["MyKey"];

讀取 connectionStrings

string connStr = ConfigurationManager.ConnectionStrings["MyDb"].ConnectionString;

修改並儲存 (需寫入權限)

var config = WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings["MyKey"].Value = "NewValue";
config.Save(); // 觸發應用程式重啟

加密敏感區段 (如 connectionStrings)

// 命令列工具
aspnet_regiis -pef "connectionStrings" "網站實體路徑" -prov "DataProtectionConfigurationProvider"

// 程式碼加密
var section = config.GetSection("connectionStrings");
if (!section.SectionInformation.IsProtected)
{
    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
    config.Save();
}

最佳實踐建議

  • 敏感資訊加密:連線字串、API 金鑰務必加密區段。
  • 環境差異外部化:使用 `configSource` 屬性將區段拆分至外部檔案 (如 `connectionStrings.config`),部署時僅替換外部檔。
  • 避免硬式編碼路徑:使用 `~`、`Server.MapPath`、`HttpRuntime.AppDomainAppPath` 取得實體路徑。
  • 版本控管:web.config 納入版控,但生產環境專屬設定 (如真實連線字串) 以 `.config.transform` 或 CI/CD 變數注入。

總結

理解 web.config 的層級架構、搜尋順序與區段用途,能靈活管理應用程式設定,實現開發與部署分離、敏感資料保護與環境差異隔離。

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