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>
<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)) { ... }
優點:部署時只改設定檔,無需重編譯。
<appSettings>
<add key="AllowedImageTypes" value=".jpg;.png;.gif" />
<add key="UploadPath" value="~/Uploads/" />
</appSettings>
讀取:`ConfigurationManager.AppSettings["AllowedImageTypes"]`
| 子區段 | 關鍵屬性/用途 |
|---|---|
<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) |
<modules>、<handlers> 取代舊版 `<security>、<rewrite> (URL Rewrite Module) 等