| 層級 | 檔案位置 | 影響範圍 | 優先序 |
| 機器層級 | C:\Windows\Microsoft.NET\Framework[64]\[版本]\CONFIG\machine.config | 該機器上所有 ASP.NET 應用程式 | 最低 (被 Web.config 覆蓋) |
| 應用程式層級 | 專案根目錄 web.config | 單一應用程式 | 最高 (覆蓋 machine.config) |
修改 Machine.config (機器層級,影響所有網站)
64 位元系統路徑
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG\machine.config
32 位元系統路徑
C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config
編輯步驟
- 以系統管理員身分開啟記事本,開啟上述
machine.config
- 尋找
<system.web> 區段
- 在
<authorization> 節點**之前**插入 <httpRuntime> 設定:
<system.web>
<!-- 新增此行:maxRequestLength=40960 KB (40 MB),executionTimeout=90 秒 -->
<httpRuntime executionTimeout="90" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false"
minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" />
<authorization>
<allow users="*" />
</authorization>
...
</system.web>
- 儲存檔案 (需管理員權限)
- 重啟 IIS:
iisreset 或「服務」重啟 World Wide Web Publishing Service
修改 Web.config (應用程式層級,建議做法)
**最佳實務:僅修改專案的 web.config,不動 machine.config**,避免影響同機器其他網站,且隨專案部署遷移。
<configuration>
<system.web>
<httpRuntime
maxRequestLength="102400" <!-- 100 MB (KB) -->
executionTimeout="600" <!-- 10 分鐘 (秒) -->
requestLengthDiskThreshold="256" <!-- 256 KB 以上寫磁碟 -->
enableVersionHeader="false" <!-- 安全性 -->
/>
</system.web>
<!-- IIS 7+ 整合模式額外需設定 -->
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="104857600" /> <!-- 100 MB (Bytes) -->
</requestLimits>
</requestFiltering>
</security>
</system.webServer>
</configuration>
關鍵參數對照表
| 參數 | 位置 | 單位 | 預設值 | 建議大檔值 | 說明 |
| maxRequestLength | system.web/httpRuntime | KB | 4096 | 102400 (100 MB) | ASP.NET 管線層級限制 |
| executionTimeout | system.web/httpRuntime | 秒 | 110 | 600 (10 分鐘) | 請求處理逾時 |
| requestLengthDiskThreshold | system.web/httpRuntime | KB | 256 | 256 | 超過此大小改用磁碟暫存 |
| maxAllowedContentLength | system.webServer/security/requestFiltering/requestLimits | Bytes | 30000000 (30 MB) | 104857600 (100 MB) | IIS 7+ 請求過濾層級限制 |
單位陷阱提醒 ⚠
maxRequestLength:**KB** (千位元組)
maxAllowedContentLength:**Bytes** (位元組)
- 換算:
100 MB = 100 * 1024 = 102400 KB = 104857600 Bytes
驗證設定是否生效
- 建立測試頁面,上傳 50 MB 檔案
- 觀察:成功上傳 → 設定生效;失敗顯示 400/404/413 → 檢查單位、IIS 重啟、應用程式集區回收
- 開發者工具 Network 面板確認 Request/Response 標頭
進階:超大檔 (100MB+) 架構建議
單一請求傳輸 100MB+ 易發生逾時、記憶體壓力、網路中斷重傳困難。企業級系統採用:
- 分塊上傳 (Chunked Upload):前端切割 1-5 MB 片段,並行上傳,後端合併
- 斷點續傳:記錄已上傳片段,中斷後續傳
- 直傳雲端儲存:前端取得簽名 URL,直接上傳至 Azure Blob / AWS S3 / 阿里云 OSS,後端僅驗證回調
- 流式處理:ASP.NET Core
IFormFile / MultipartReader 邊收邊寫磁碟,不載入記憶體
總結
解決 ASP.NET 4MB 上傳限制:**優先修改專案 web.config** 設定 httpRuntime.maxRequestLength (KB) 與 executionTimeout (秒);IIS 7+ 必須同步設定 requestFiltering.maxAllowedContentLength (Bytes)。**單位換算務必精確**。機器層級 machine.config 修改雖有效但影響面廣,不建議常規使用。大檔上傳架構請採用分塊/直傳雲端模式。
- 上一篇文章: Visual Studio 2005 開啟 VS 2008 專案的兩種降級相容方法</x2Title>
<xTitle>Visual Studio 2005 開啟 VS 2008 專案的兩種降級相容方法
- 下一篇文章: ASP.NET Web API POST 參數為 Null 疑難雜症:缺少 "=" 前綴導致模型繫結失效
Copyright ©
程式碼之家 All Rights Reserved