萬盛學電腦網

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

ASP.NET 執行階段錯誤與 customErrors 設定完整指南

預設錯誤頁面內容

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 頁面保留網站導航與搜尋功能
copyright © 萬盛學電腦網 all rights reserved