MVC 錯誤處理1

來源:互聯網
上載者:User

標籤:

執行個體1.

        /// <summary>        /// 錯誤處理        /// 404 處理        /// </summary>        protected void Application_Error(object sender, EventArgs e)        {            //判斷請求方式            if (Request.HttpMethod == "GET")            {                // 擷取錯誤                HttpException exception = Server.GetLastError() as HttpException;                if (exception != null)                {                    if (exception.GetHttpCode() == 404)                    {                        //輸出指定的字串                        Response.Clear();                        //Response.Write("code:404");                        //輸出指定controller下的內容                        RouteData routeData = new RouteData();                        routeData.Values.Add("controller", "ViewOne");                        routeData.Values.Add("action", "TempTwo");                        routeData.Values.Add("name", "zhangsan");                        IController one = new ViewOneController();                        one.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));                        /*                         *  如果不指定 結束輸出的話,則還是會執行架構的自動處理(會清空自己輸出的內容)                         *  如果指定結束的話,狀態代碼是200,而不是400,所以需要自己手動指定狀態代碼                         */                        Response.StatusCode = 404;                        Response.End();                        Context.ClearError();                    }                }            }        }

 

執行個體2.

MVC中,有一個Filter可以捕捉錯誤,但是它的用法是利用Attribute來實現的,而且只能加在Controller和Action上,所以不能捕捉別出的錯誤

其實理論上所有的錯誤肯定產生於Controller中,但有2種情況下,就不會被捕捉了

1、頁面不存在的時候,找不到對應的Controller,那沒有任何Controller被執行,所以自然也不會捕捉到錯誤了

2、在 IAuthorizationFilter 下發生錯誤的時候,錯誤捕捉代碼在IExceptionFilter中,而IAuthorizationFilter的優先權高於IExceptionFilter,所以也就捕捉不到了

protected void Application_Error(object sender, EventArgs e)          {              Exception exception = Server.GetLastError();              Response.Clear();              HttpException httpException = exception as HttpException;              RouteData routeData = new RouteData();              routeData.Values.Add("controller", "Error");              if (httpException == null)              {                  routeData.Values.Add("action", "Index");              }              else //It‘s an Http Exception, Let‘s handle it.              {                  switch (httpException.GetHttpCode())                  {                      case 404:                          // Page not found.                          routeData.Values.Add("action", "HttpError404");                          break;                      case 500:                          // Server error.                          routeData.Values.Add("action", "HttpError500");                          break;                      // Here you can handle Views to other error codes.                      // I choose a General error template                        default:                          routeData.Values.Add("action", "General");                          break;                  }              }              // Pass exception details to the target error View.              routeData.Values.Add("error", exception.Message);              // Clear the error on server.              Server.ClearError();              // Call target Controller and pass the routeData.              IController errorController = new WEB.Controllers.ErrorController();              errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));          }   

 

把這段代碼放到 Global.asax 中,並且建立一個 Controller 叫做 Error

namespace MVC.Controllers  {      public class ErrorController : Controller      {          public ActionResult Index(string error)          {              ViewData["Title"] = "WebSite 網站內部錯誤";              ViewData["Description"] = error;              return View("Index");          }          public ActionResult HttpError404(string error)          {              ViewData["Title"] = "HTTP 404- 無法找到檔案";              ViewData["Description"] = error;              return View("Index");          }          public ActionResult HttpError500(string error)          {              ViewData["Title"] = "HTTP 500 - 內部伺服器錯誤";              ViewData["Description"] = error;              return View("Index");          }          public ActionResult General(string error)          {              ViewData["Title"] = "HTTP 發生錯誤";              ViewData["Description"] = error;              return View("Index");          }      }  }   
這樣,就可以捕捉所有錯誤了。

但其實,這樣也不是完美的,因為如果你參考了我第一個問題中,在IIS6下不修改IIS設定,運行了MVC,那當尾碼名不是.aspx的時候,錯誤不會被捕捉

因為這時候輸入的地址根本沒有交給網站來處理,IIS直接拋出了錯誤,因為IIS認為這個尾碼名不是你所能執行

 

MVC 錯誤處理1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.