預設錯誤頁面內容
Runtime Error
Description: An application error occurred on the server. The current custom error settings
for this application prevent the details of the application error from being viewed remotely
(for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be viewable on remote machines,
please create a <customErrors> tag within a "web.config" configuration file located in the root
directory of the current web application. This <customErrors> tag should then have its "mode"
attribute set to "Off".
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
Notes: The current error page you are seeing can be replaced by a custom error page by modifying
the "defaultRedirect" attribute of the application's <customErrors> configuration tag to point
to a custom error page URL.
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
</system.web>
</configuration>
customErrors 三種模式
| 模式 | 本機瀏覽 | 遠端瀏覽 | 適用環境 |
| Off | 詳細錯誤 | 詳細錯誤 | 開發/測試環境 |
| On | 自訂錯誤頁 | 自訂錯誤頁 | 生產環境 (預設) |
| RemoteOnly | 詳細錯誤 | 自訂錯誤頁 | 生產環境 (推薦,利於本機除錯) |
完整設定範例
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="/Error/GeneralError.aspx">
<error statusCode="404" redirect="/Error/NotFound.aspx" />
<error statusCode="500" redirect="/Error/ServerError.aspx" />
<error statusCode="403" redirect="/Error/AccessDenied.aspx" />
</customErrors>
</system.web>
</configuration>
進階技巧
1. 程式碼中存取錯誤詳情 (RemoteOnly 時)
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
// 記錄完整堆疊追蹤至 Log
Logger.Error(ex);
// 可選:清除錯誤避免顯示預設頁面
// Server.ClearError();
}
2. MVC 專案錯誤處理
- 全域錯誤處理:`Global.asax` `Application_Error` 或 `HandleErrorAttribute`
- 自訂錯誤頁面:`Views/Shared/Error.cshtml`
- 生產環境仍需設定 `` (IIS 7+ 需 `` 配合)
3. IIS 7+ 整合模式雙重設定
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly" existingResponse="Replace">
<remove statusCode="404" />
<error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL" />
<error statusCode="500" path="/Error/ServerError" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
安全性最佳實踐
- ✅ 生產環境絕不使用 `mode="Off"`
- ✅ 自訂錯誤頁面不洩露堆疊追蹤、SQL、路徑等敏感資訊
- ✅ 記錄完整錯誤至伺服器端 Log (ELMah, Serilog, NLog)
- ✅ 友善錯誤訊息引導使用者 (「系統暫時不可用,請稍後再試」)
- ✅ 404 頁面保留網站導航與搜尋功能