Asp.net-Mvc

ASP.NET MVC 中的全域錯誤處理(控制器外部)

  • February 6, 2018

假設我將以下程式碼放在 ASP.NET MVC 站點的母版頁中的某處:

throw new ApplicationException("TEST");

即使有一個

$$ HandleError $$屬性放在我的控制器上,這個異常仍然冒泡。我該如何處理這樣的錯誤?我希望能夠路由到錯誤頁面並且仍然能夠記錄異常詳細資訊。 處理這樣的事情的最佳方法是什麼?

編輯:我正在考慮的一種解決方案是添加一個新控制器:UnhandledErrorController。我可以在 Global.asax 中放入一個 Application_Error 方法,然後重定向到這個控制器(它決定如何處理異常)?

注意:customErrors web.config 元素中的 defaultRedirect 不會傳遞異常資訊。

由於 MVC 建立在 asp.net 之上,您應該能夠在web.config中定義一個全域錯誤頁面,就像您可以在 Web 表單中一樣。

  <customErrors mode="On" defaultRedirect="~/ErrorHandler" />

啟用自定義錯誤:

<customErrors mode="On" defaultRedirect="~/Error">
   <error statusCode="401" redirect="~/Error/Unauthorized" />
   <error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>

並重定向到自定義錯誤控制器:

[HandleError]
public class ErrorController : BaseController
{
   public ErrorController ()
   {
   }

   public ActionResult Index ()
   {
       Response.StatusCode = (int)HttpStatusCode.InternalServerError;
       return View ("Error");
   }

   public ActionResult Unauthorized ()
   {
       Response.StatusCode = (int)HttpStatusCode.Unauthorized;
       return View ("Error401");
   }

   public ActionResult NotFound ()
   {
       string url = GetStaticRoute (Request.QueryString["aspxerrorpath"] ?? Request.Path);
       if (!string.IsNullOrEmpty (url))
       {
           Notify ("Due to a new web site design the page you were looking for no longer exists.", false);
           return new MovedPermanentlyResult (url);
       }

       Response.StatusCode = (int)HttpStatusCode.NotFound;
       return View ("Error404");
   }
}

引用自:https://stackoverflow.com/questions/1358406