ASP.NET MVC 如何客製錯誤畫面 (Custom Error Page)


  1. 說明
    1. Throw Exception
    2. Web.config to Enable Deployed Error Page
    3. Custom Error Page

筆記如何從 ASP.NET MVC 客製錯誤訊息畫面以及如何在開發階段顯示 Deploy 後的錯誤畫面。

logo

說明

Throw Exception

在 Controller 可以刻意的引發錯誤來觀看錯誤訊息,而在開發環境中可以看到詳細的錯誤資訊,部署後使用者則只能看到 Error.cshtml 中的錯誤訊息,避免資訊暴露。

throw new HttpException("Error Page");

Web.config to Enable Deployed Error Page

藉由在 web.config 設定,可以在開發階段可看部署後使用者看到的錯誤訊息。

<system.web>
  <customErrors mode="On"/>
</system.web>

Custom Error Page

錯誤訊息是來自 ~/Views/Shared/Error.cshtml 中,藉由設定這個 View 就可以達到客製訊息的效果。

實用的客製樣板

@model System.Web.Mvc.HandleErrorInfo

@{ ViewBag.Title = "錯誤"; }

<div class="container bg-white text-danger p-5 border">
    <h2 class="text-danger font-weight-bolder text-center mb-4">錯誤,處理您的要求時發生錯誤。</h2>
    <div class="text-dark">
        <h3>@Model.Exception.Message</h3>

        <div>Http Status Code:@this.Response.StatusCode</div>

        <div>Session:@this.Session.SessionID</div>

        <div>Server Name:@this.Server.MachineName</div>

        <div>User Information:@this.User.Identity.Name</div>

        <div>URL:@this.Request.Url</div>

        <div class="bg-secondary p-2 mt-2 text-white">
            錯誤處理:請將本畫面截圖,提供開發人員參考。
        </div>
    </div>
</div>