萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

.NET Web.config 完整配置指南

配置檔層級與載入機制

  • machine.config:機器層級,所有 .NET 應用程式共享。
  • web.config:應用程式層級,覆寫機器設定,IIS 啟動時載入並快取,檔案變更自動重載。

根結構

<configuration xmlns="https://schemas.microsoft.com/.NetConfiguration/v2.0">
  <configSections />
  <appSettings />
  <connectionStrings />
  <system.web />
  <system.webServer /> <!-- 僅 IIS 7+ 整合模式生效 -->
</configuration>

主要區段詳細說明

1. <connectionStrings> - 資料庫連線字串

<connectionStrings>
  <add name="MainDB" connectionString="Data Source=.;Initial Catalog=MyDB;User ID=sa;Password=123" providerName="System.Data.SqlClient" />
  <add name="BackupDB" connectionString="Data Source=10.0.0.52;Initial Catalog=BakDB;User ID=user;Password=pwd" />
</connectionStrings>

程式碼讀取:

string connStr = ConfigurationManager.ConnectionStrings["MainDB"].ConnectionString;
using (var conn = new SqlConnection(connStr)) { ... }

優點:部署時只改設定檔,無需重編譯。

2. <appSettings> - 應用程式設定

<appSettings>
  <add key="AllowedImageTypes" value=".jpg;.png;.gif" />
  <add key="UploadPath" value="~/Uploads/" />
</appSettings>

讀取:`ConfigurationManager.AppSettings["AllowedImageTypes"]`

3. <system.web> - ASP.NET 核心設定

子區段關鍵屬性/用途
<compilation>`debug="true/false"` 開發/生產環境切換;`targetFramework` 指定編譯版本
<authentication>`mode="Forms|Windows|Passport|None"` 身分驗證模式
<customErrors>`mode="On|Off|RemoteOnly"`、`defaultRedirect`、子 ``
<httpHandlers>對應副檔名/動詞至處理器,如封鎖 ``
<httpRuntime>`maxRequestLength` (KB) 上傳大小限制、`executionTimeout` 秒數、`appRequestQueueLimit` 佇列長度
<pages>`buffer`、`enableViewStateMac`、`viewStateEncryptionMode` 等頁面預設行為
<sessionState>`mode="InProc|StateServer|SQLServer"`、`timeout` 分鐘、`cookieless`
<trace>`enabled="true"`、`pageOutput="false"`、`requestLimit` 追蹤記錄數
<trust>`level="Full|High|Medium|Low|Minimal"` 程式碼存取安全性 (CAS)

4. <system.webServer> - IIS 7+ 整合模式專屬

  • <modules>、<handlers> 取代舊版 ``、``
  • <security>、<rewrite> (URL Rewrite Module) 等
  • 經典模式會**忽略**此區段

最佳實務

  1. 敏感資訊(連線字串密碼、API Key)勿直接寫入,改用 `` 加密或 Azure Key Vault / AWS Secrets Manager。
  2. 利用 `configSource` 屬性將大區段拆分為外部檔案:``
  3. 部署轉換 (`Web.Release.config`) 自動切換 `debug="false"`、連線字串、移除追蹤等。
  4. 定期審查 `` 避免生產環境洩露堆疊追蹤。
copyright © 萬盛學電腦網 all rights reserved