2017年9月9日 星期六

[MVC] Custom Errors, HandleError Attribute

  • Custom Errors

    • 建置基礎的 Web 應用程式中設定自訂錯誤時,收到自訂錯誤訊息
    • Required Attribute (<customErrors> Element)
AttributeOptionDescription
Mode   Specifies whether custom errors are enabled, disabled, or shown only to remote clients.
   OnSpecifies that custom errors are enabled. If no defaultRedirect is specified, users see a generic error.
   OffSpecifies that custom errors are disabled. This allows display of detailed errors.
   RemoteOnlySpecifies that custom errors are shown only to remote clients and ASP.NET errors are shown to the local host. This is the default.
    • 步驟 1:設定 Web.Config
<!-- Web.Config Configuration File -->

<configuration>
    <system.web>
        <customErrors mode="On"/>
    </system.web>
</configuration>
    • 步驟 2:設定自訂錯誤頁面 Error.cshrml 
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Error</title>
</head>
<body>
    <hgroup>
        <h1>Error.</h1>
        <h2>An error occurred while processing your request.</h2>
    </hgroup>
</body>
</html>
    • 步驟 3-1:Action Method 或 Conroller 加入 [HandleError]
using System.Web.Mvc;

namespace DemoError.Controllers
{
    //[HandleError]
    public class DemoErrorController : Controller
    {
        //[HandleError]
        public ActionResult Index()
        {
            int i = 0;

            int j = 10 / i;

            return View();
        }
    }
} 
    • 步驟 3-2:Web Application 等級需在 Global.asax 中 Application_Start 進行設定
    • Demo Page

  • HandleError 1 (WEB)

    • 錯誤相關處理並傳回值,指出發送器是否會在某些情況下,中止工作階段和執行個體內容
    • 步驟 1:設定 Web.Config
<!-- Web.Config Configuration File -->

<configuration>
    <system.web>
        <customErrors mode="On">
            <error redirect="~/404.html" statuscode="404">
        </customErrors>
    </system.web>
</configuration>
    • 步驟 2:加入 404.cshtml
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title></title>
</head>
<body>
    <h1>404</h1>
</body>
</html>
    • Demo Page

  • HandleError 2 (IIS)

    • 上方為 WEB 中進行設定,如需再 IIS 上進行設定如下:
  <system.webServer>
    <httpErrors errorMode="Custom">
      <remove statusCode="404"/>
      <error statusCode="404" path="/404.html" responseMode="ExecuteURL"/>
    </httpErrors>
  </system.webServer>

沒有留言:

張貼留言